| Differences between
and this patch
- a/Source/JavaScriptCore/ChangeLog +268 lines
Lines 1-3 a/Source/JavaScriptCore/ChangeLog_sec1
1
2016-04-03  Caitlin Potter  <caitp@igalia.com>
2
3
        [JSC] implement async functions proposal
4
        https://bugs.webkit.org/show_bug.cgi?id=156147
5
6
        Reviewed by NOBODY (OOPS!).
7
8
        Adds support for `async` functions, proposed in https://tc39.github.io/ecmascript-asyncawait/.
9
10
        On the front-end side, "await" becomes a contextual keyword when used within an async function,
11
        which triggers parsing an AwaitExpression. "await" becomes an illegal identifier name within
12
        these contexts. The bytecode generated from an "await" expression is identical to that generated
13
        in a "yield" expression in a Generator, as AsyncFunction reuses generator's state machine mechanism.
14
15
        There are numerous syntactic forms for language features, including a variation on ArrowFunctions,
16
        requiring the keyword `async` to precede ArrowFormalParameters, and similarly, MethodDefinitions,
17
        which are ordinary MethodDefinitions preceded by the keyword `async`.
18
19
        An async function desugars to the following:
20
21
        ```
22
        async function asyncFn() {
23
        }
24
25
        becomes:
26
27
        function asyncFn() {
28
            let generator = {
29
                @generatorNext: function(@generator, @generatorState, @generatorValue, @generatorResumeMode) {
30
                  // generator state machine stuff here
31
                },
32
                @generatorState: 0,
33
                @generatorThis: this,
34
                @generatorFrame: null
35
            };
36
            return @asyncFunctionResume(generator, undefined, GeneratorResumeMode::NormalMode);
37
        }
38
        ```
39
40
        `@asyncFunctionResume()` is similar to `@generatorResume`, with the exception that it will wrap the
41
        result of invoking `@generatorNext()` in a Promise, and will avoid allocating an iterator result
42
        object.
43
44
        If the generator has yielded (an AwaitExpression has occurred), resumption will occur automatically
45
        once the await-expression operand is finished, via Promise chaining.
46
47
        * CMakeLists.txt:
48
        * DerivedSources.make:
49
        * JavaScriptCore.xcodeproj/project.pbxproj:
50
        * builtins/AsyncFunctionPrototype.js: Added.
51
        (asyncFunctionResume):
52
        * bytecode/BytecodeList.json:
53
        * bytecode/BytecodeUseDef.h:
54
        (JSC::computeUsesForBytecodeOffset):
55
        (JSC::computeDefsForBytecodeOffset):
56
        * bytecode/CodeBlock.cpp:
57
        (JSC::CodeBlock::dumpBytecode):
58
        (JSC::CodeBlock::finishCreation):
59
        * bytecode/UnlinkedCodeBlock.h:
60
        (JSC::UnlinkedCodeBlock::isAsyncArrowFunction):
61
        * bytecompiler/BytecodeGenerator.cpp:
62
        (JSC::BytecodeGenerator::BytecodeGenerator):
63
        (JSC::BytecodeGenerator::emitNewFunctionExpressionCommon):
64
        (JSC::BytecodeGenerator::emitNewArrowFunctionExpression):
65
        (JSC::BytecodeGenerator::emitNewMethodDefinition):
66
        (JSC::BytecodeGenerator::emitNewFunction):
67
        (JSC::BytecodeGenerator::emitLoadArrowFunctionLexicalEnvironment):
68
        * bytecompiler/BytecodeGenerator.h:
69
        (JSC::BytecodeGenerator::makeFunction):
70
        * bytecompiler/NodesCodegen.cpp:
71
        (JSC::FunctionNode::emitBytecode):
72
        * jit/JIT.cpp:
73
        (JSC::JIT::privateCompileMainPass):
74
        * jit/JIT.h:
75
        * jit/JITOpcodes.cpp:
76
        (JSC::JIT::emit_op_new_async_func):
77
        (JSC::JIT::emitNewFuncExprCommon):
78
        (JSC::JIT::emit_op_new_async_func_exp):
79
        * jit/JITOperations.cpp:
80
        * jit/JITOperations.h:
81
        * llint/LLIntSlowPaths.cpp:
82
        (JSC::LLInt::LLINT_SLOW_PATH_DECL):
83
        * llint/LLIntSlowPaths.h:
84
        * llint/LowLevelInterpreter.asm:
85
        * parser/Parser.cpp:
86
        (JSC::Parser<LexerType>::Parser):
87
        (JSC::Parser<LexerType>::parseInner):
88
        (JSC::Parser<LexerType>::parseAsyncFunctionSourceElements):
89
        (JSC::Parser<LexerType>::parseStatementListItem):
90
        (JSC::Parser<LexerType>::parseVariableDeclarationList):
91
        (JSC::Parser<LexerType>::parseDestructuringPattern):
92
        (JSC::Parser<LexerType>::parseFormalParameters):
93
        (JSC::stringForFunctionMode):
94
        (JSC::Parser<LexerType>::parseFunctionParameters):
95
        (JSC::Parser<LexerType>::parseFunctionInfo):
96
        (JSC::Parser<LexerType>::parseAsyncFunctionDeclaration):
97
        (JSC::Parser<LexerType>::parseClass):
98
        (JSC::Parser<LexerType>::parseExpressionOrLabelStatement):
99
        (JSC::Parser<LexerType>::parseExportDeclaration):
100
        (JSC::Parser<LexerType>::parseAssignmentExpression):
101
        (JSC::Parser<LexerType>::parseProperty):
102
        (JSC::Parser<LexerType>::parsePropertyMethod):
103
        (JSC::Parser<LexerType>::parseAsyncFunctionExpression):
104
        (JSC::Parser<LexerType>::parsePrimaryExpression):
105
        (JSC::Parser<LexerType>::parseArrowFunctionExpression):
106
        (JSC::Parser<LexerType>::parseUnaryExpression):
107
        * parser/Parser.h:
108
        (JSC::Scope::Scope):
109
        (JSC::Scope::setSourceParseMode):
110
        (JSC::Scope::isAsyncFunction):
111
        (JSC::Scope::isAsyncFunctionBoundary):
112
        (JSC::Scope::isModule):
113
        (JSC::Scope::setIsFunction):
114
        (JSC::Scope::setIsAsyncArrowFunction):
115
        (JSC::Scope::setIsAsyncFunction):
116
        (JSC::Scope::setIsAsyncFunctionBody):
117
        (JSC::Scope::setIsAsyncArrowFunctionBody):
118
        (JSC::Parser::AllowAwaitOverride::AllowAwaitOverride):
119
        (JSC::Parser::AllowAwaitOverride::~AllowAwaitOverride):
120
        (JSC::Parser::declarationTypeToVariableKind):
121
        (JSC::Parser::closestParentOrdinaryFunctionNonLexicalScope):
122
        (JSC::Parser::pushScope):
123
        (JSC::Parser::popScopeInternal):
124
        (JSC::Parser::isAwaitKeyword):
125
        (JSC::Parser::isAsyncKeyword):
126
        (JSC::Parser::isDisallowedIdentifierAwait):
127
        (JSC::Parser::disallowedIdentifierAwaitReason):
128
        * parser/ParserModes.h:
129
        (JSC::isFunctionParseMode):
130
        (JSC::isAsyncFunctionParseMode):
131
        (JSC::isAsyncArrowFunctionParseMode):
132
        (JSC::isAsyncFunctionWrapperParseMode):
133
        (JSC::isAsyncFunctionBodyParseMode):
134
        (JSC::isModuleParseMode):
135
        (JSC::isProgramParseMode):
136
        * runtime/AsyncFunctionConstructor.cpp: Added.
137
        (JSC::AsyncFunctionConstructor::AsyncFunctionConstructor):
138
        (JSC::AsyncFunctionConstructor::finishCreation):
139
        (JSC::callAsyncFunctionConstructor):
140
        (JSC::constructAsyncFunctionConstructor):
141
        (JSC::AsyncFunctionConstructor::getCallData):
142
        (JSC::AsyncFunctionConstructor::getConstructData):
143
        * runtime/AsyncFunctionConstructor.h: Added.
144
        (JSC::AsyncFunctionConstructor::create):
145
        (JSC::AsyncFunctionConstructor::createStructure):
146
        * runtime/AsyncFunctionPrototype.cpp: Added.
147
        (JSC::AsyncFunctionPrototype::AsyncFunctionPrototype):
148
        (JSC::AsyncFunctionPrototype::finishCreation):
149
        * runtime/AsyncFunctionPrototype.h: Added.
150
        (JSC::AsyncFunctionPrototype::create):
151
        (JSC::AsyncFunctionPrototype::createStructure):
152
        * runtime/CodeCache.cpp:
153
        (JSC::CodeCache::getFunctionExecutableFromGlobalCode):
154
        * runtime/CommonIdentifiers.h:
155
        * runtime/FunctionConstructor.cpp:
156
        (JSC::constructFunctionSkippingEvalEnabledCheck):
157
        * runtime/FunctionConstructor.h:
158
        * runtime/JSAsyncFunction.cpp: Added.
159
        (JSC::JSAsyncFunction::JSAsyncFunction):
160
        (JSC::JSAsyncFunction::createImpl):
161
        (JSC::JSAsyncFunction::create):
162
        (JSC::JSAsyncFunction::createWithInvalidatedReallocationWatchpoint):
163
        * runtime/JSAsyncFunction.h: Added.
164
        (JSC::JSAsyncFunction::allocationSize):
165
        (JSC::JSAsyncFunction::createStructure):
166
        * runtime/JSGlobalObject.cpp:
167
        (JSC::JSGlobalObject::init):
168
        * runtime/JSGlobalObject.h:
169
        (JSC::JSGlobalObject::asyncFunctionPrototype):
170
        (JSC::JSGlobalObject::asyncFunctionStructure):
171
        * tests/es6.yaml:
172
        * tests/es6/async-await-basic.js: Added.
173
        (shouldBe):
174
        (shouldBeAsync):
175
        (shouldThrow):
176
        (shouldThrowAsync):
177
        (async.asyncFunctionForProto):
178
        (Object.getPrototypeOf.async):
179
        (Object.getPrototypeOf.async.method):
180
        (async.asyncNonConstructorDecl):
181
        (shouldThrow.new.async):
182
        (shouldThrow.new.async.nonConstructor):
183
        (async.asyncDecl):
184
        (async):
185
        (async.f):
186
        (MyError):
187
        (async.asyncDeclThrower):
188
        (shouldThrowAsync.async):
189
        (resolveLater):
190
        (rejectLater):
191
        (async.resumeAfterNormal):
192
        (O.async.resumeAfterNormal):
193
        (resumeAfterNormalArrow.async):
194
        (async.resumeAfterThrow):
195
        (O.async.resumeAfterThrow):
196
        (resumeAfterThrowArrow.async):
197
        (catch):
198
        * tests/es6/async-await-mozilla.js: Added.
199
        (shouldBe):
200
        (shouldBeAsync):
201
        (shouldThrow):
202
        (shouldThrowAsync):
203
        (assert):
204
        (shouldThrowSyntaxError):
205
        (mozSemantics.async.empty):
206
        (mozSemantics.async.simpleReturn):
207
        (mozSemantics.async.simpleAwait):
208
        (mozSemantics.async.simpleAwaitAsync):
209
        (mozSemantics.async.returnOtherAsync):
210
        (mozSemantics.async.simpleThrower):
211
        (mozSemantics.async.delegatedThrower):
212
        (mozSemantics.async.tryCatch):
213
        (mozSemantics.async.tryCatchThrow):
214
        (mozSemantics.async.wellFinally):
215
        (mozSemantics.async.finallyMayFail):
216
        (mozSemantics.async.embedded.async.inner):
217
        (mozSemantics.async.embedded):
218
        (mozSemantics.async.fib):
219
        (mozSemantics.async.isOdd.async.isEven):
220
        (mozSemantics.async.isOdd):
221
        (mozSemantics.hardcoreFib.async.fib2):
222
        (mozSemantics.namedAsyncExpr.async.simple):
223
        (mozSemantics.async.executionOrder.async.first):
224
        (mozSemantics.async.executionOrder.async.second):
225
        (mozSemantics.async.executionOrder.async.third):
226
        (mozSemantics.async.executionOrder):
227
        (mozSemantics.async.miscellaneous):
228
        (mozSemantics.thrower):
229
        (mozSemantics.async.defaultArgs):
230
        (mozSemantics.shouldThrow):
231
        (mozSemantics):
232
        (mozMethods.X):
233
        (mozMethods.X.prototype.async.getValue):
234
        (mozMethods.X.prototype.setValue):
235
        (mozMethods.X.prototype.async.increment):
236
        (mozMethods.X.prototype.async.getBaseClassName):
237
        (mozMethods.X.async.getStaticValue):
238
        (mozMethods.Y.prototype.async.getBaseClassName):
239
        (mozMethods.Y):
240
        (mozFunctionNameInferrence.async.test):
241
        (mozSyntaxErrors):
242
        * tests/es6/async-await-reserved-word.js: Added.
243
        (assert):
244
        (shouldThrowSyntaxError):
245
        * tests/es6/async_arrow_functions_lexical_arguments_binding.js: Added.
246
        (shouldBe):
247
        (shouldBeAsync):
248
        (shouldThrowAsync):
249
        (noArgumentsArrow2.async):
250
        * tests/es6/async_arrow_functions_lexical_new.target_binding.js: Added.
251
        (shouldBe):
252
        (shouldBeAsync):
253
        (shouldThrowAsync):
254
        (C1):
255
        (C2):
256
        (shouldThrowAsync.async):
257
        * tests/es6/async_arrow_functions_lexical_super_binding.js: Added.
258
        (shouldBe):
259
        (shouldBeAsync):
260
        (BaseClass.prototype.baseClassValue):
261
        (BaseClass):
262
        (ChildClass.prototype.asyncSuperProp):
263
        (ChildClass):
264
        * tests/es6/async_arrow_functions_lexical_this_binding.js: Added.
265
        (shouldBe):
266
        (shouldBeAsync):
267
        (d.y):
268
1
2016-04-03  Yusuke Suzuki  <utatane.tea@gmail.com>
269
2016-04-03  Yusuke Suzuki  <utatane.tea@gmail.com>
2
270
3
        Unreviewed, turn ES6 for-in loop test success
271
        Unreviewed, turn ES6 for-in loop test success
- a/Source/JavaScriptCore/CMakeLists.txt +4 lines
Lines 606-611 set(JavaScriptCore_SOURCES a/Source/JavaScriptCore/CMakeLists.txt_sec1
606
    runtime/ArrayConstructor.cpp
606
    runtime/ArrayConstructor.cpp
607
    runtime/ArrayIteratorPrototype.cpp
607
    runtime/ArrayIteratorPrototype.cpp
608
    runtime/ArrayPrototype.cpp
608
    runtime/ArrayPrototype.cpp
609
    runtime/AsyncFunctionConstructor.cpp
610
    runtime/AsyncFunctionPrototype.cpp
609
    runtime/BasicBlockLocation.cpp
611
    runtime/BasicBlockLocation.cpp
610
    runtime/BooleanConstructor.cpp
612
    runtime/BooleanConstructor.cpp
611
    runtime/BooleanObject.cpp
613
    runtime/BooleanObject.cpp
Lines 679-684 set(JavaScriptCore_SOURCES a/Source/JavaScriptCore/CMakeLists.txt_sec2
679
    runtime/JSArrayBufferPrototype.cpp
681
    runtime/JSArrayBufferPrototype.cpp
680
    runtime/JSArrayBufferView.cpp
682
    runtime/JSArrayBufferView.cpp
681
    runtime/JSArrayIterator.cpp
683
    runtime/JSArrayIterator.cpp
684
    runtime/JSAsyncFunction.cpp
682
    runtime/JSBoundFunction.cpp
685
    runtime/JSBoundFunction.cpp
683
    runtime/JSBoundSlotBaseFunction.cpp
686
    runtime/JSBoundSlotBaseFunction.cpp
684
    runtime/JSCJSValue.cpp
687
    runtime/JSCJSValue.cpp
Lines 1202-1207 set(JavaScriptCore_BUILTINS_SOURCES a/Source/JavaScriptCore/CMakeLists.txt_sec3
1202
    ${JAVASCRIPTCORE_DIR}/builtins/ArrayConstructor.js
1205
    ${JAVASCRIPTCORE_DIR}/builtins/ArrayConstructor.js
1203
    ${JAVASCRIPTCORE_DIR}/builtins/ArrayIteratorPrototype.js
1206
    ${JAVASCRIPTCORE_DIR}/builtins/ArrayIteratorPrototype.js
1204
    ${JAVASCRIPTCORE_DIR}/builtins/ArrayPrototype.js
1207
    ${JAVASCRIPTCORE_DIR}/builtins/ArrayPrototype.js
1208
    ${JAVASCRIPTCORE_DIR}/builtins/AsyncFunctionPrototype.js
1205
    ${JAVASCRIPTCORE_DIR}/builtins/DatePrototype.js
1209
    ${JAVASCRIPTCORE_DIR}/builtins/DatePrototype.js
1206
    ${JAVASCRIPTCORE_DIR}/builtins/FunctionPrototype.js
1210
    ${JAVASCRIPTCORE_DIR}/builtins/FunctionPrototype.js
1207
    ${JAVASCRIPTCORE_DIR}/builtins/GeneratorPrototype.js
1211
    ${JAVASCRIPTCORE_DIR}/builtins/GeneratorPrototype.js
- a/Source/JavaScriptCore/DerivedSources.make +1 lines
Lines 84-89 JavaScriptCore_BUILTINS_SOURCES = \ a/Source/JavaScriptCore/DerivedSources.make_sec1
84
    $(JavaScriptCore)/builtins/ArrayConstructor.js \
84
    $(JavaScriptCore)/builtins/ArrayConstructor.js \
85
    $(JavaScriptCore)/builtins/ArrayIteratorPrototype.js \
85
    $(JavaScriptCore)/builtins/ArrayIteratorPrototype.js \
86
    $(JavaScriptCore)/builtins/ArrayPrototype.js \
86
    $(JavaScriptCore)/builtins/ArrayPrototype.js \
87
    $(JavaScriptCore)/builtins/AsyncFunctionPrototype.js \
87
    $(JavaScriptCore)/builtins/DatePrototype.js \
88
    $(JavaScriptCore)/builtins/DatePrototype.js \
88
    $(JavaScriptCore)/builtins/FunctionPrototype.js \
89
    $(JavaScriptCore)/builtins/FunctionPrototype.js \
89
    $(JavaScriptCore)/builtins/GeneratorPrototype.js \
90
    $(JavaScriptCore)/builtins/GeneratorPrototype.js \
- a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj +26 lines
Lines 1183-1188 a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec1
1183
		5370B4F61BF26205005C40FC /* AdaptiveInferredPropertyValueWatchpointBase.h in Headers */ = {isa = PBXBuildFile; fileRef = 5370B4F41BF25EA2005C40FC /* AdaptiveInferredPropertyValueWatchpointBase.h */; };
1183
		5370B4F61BF26205005C40FC /* AdaptiveInferredPropertyValueWatchpointBase.h in Headers */ = {isa = PBXBuildFile; fileRef = 5370B4F41BF25EA2005C40FC /* AdaptiveInferredPropertyValueWatchpointBase.h */; };
1184
		53917E7B1B7906FA000EBD33 /* JSGenericTypedArrayViewPrototypeFunctions.h in Headers */ = {isa = PBXBuildFile; fileRef = 53917E7A1B7906E4000EBD33 /* JSGenericTypedArrayViewPrototypeFunctions.h */; };
1184
		53917E7B1B7906FA000EBD33 /* JSGenericTypedArrayViewPrototypeFunctions.h in Headers */ = {isa = PBXBuildFile; fileRef = 53917E7A1B7906E4000EBD33 /* JSGenericTypedArrayViewPrototypeFunctions.h */; };
1185
		53F6BF6D1C3F060A00F41E5D /* InternalFunctionAllocationProfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 53F6BF6C1C3F060A00F41E5D /* InternalFunctionAllocationProfile.h */; settings = {ATTRIBUTES = (Private, ); }; };
1185
		53F6BF6D1C3F060A00F41E5D /* InternalFunctionAllocationProfile.h in Headers */ = {isa = PBXBuildFile; fileRef = 53F6BF6C1C3F060A00F41E5D /* InternalFunctionAllocationProfile.h */; settings = {ATTRIBUTES = (Private, ); }; };
1186
		5BD3A0671CAE325700F84BA3 /* AsyncFunctionConstructor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5BD3A0611CAE325700F84BA3 /* AsyncFunctionConstructor.cpp */; };
1187
		5BD3A0681CAE325700F84BA3 /* AsyncFunctionConstructor.h in Headers */ = {isa = PBXBuildFile; fileRef = 5BD3A0621CAE325700F84BA3 /* AsyncFunctionConstructor.h */; };
1188
		5BD3A0691CAE325700F84BA3 /* AsyncFunctionPrototype.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5BD3A0631CAE325700F84BA3 /* AsyncFunctionPrototype.cpp */; };
1189
		5BD3A06A1CAE325700F84BA3 /* AsyncFunctionPrototype.h in Headers */ = {isa = PBXBuildFile; fileRef = 5BD3A0641CAE325700F84BA3 /* AsyncFunctionPrototype.h */; };
1190
		5BD3A06B1CAE325700F84BA3 /* JSAsyncFunction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5BD3A0651CAE325700F84BA3 /* JSAsyncFunction.cpp */; };
1191
		5BD3A06E1CAE35BF00F84BA3 /* JSAsyncFunction.h in Headers */ = {isa = PBXBuildFile; fileRef = 5BD3A06D1CAE35BF00F84BA3 /* JSAsyncFunction.h */; };
1186
		5D53726F0E1C54880021E549 /* Tracing.h in Headers */ = {isa = PBXBuildFile; fileRef = 5D53726E0E1C54880021E549 /* Tracing.h */; };
1192
		5D53726F0E1C54880021E549 /* Tracing.h in Headers */ = {isa = PBXBuildFile; fileRef = 5D53726E0E1C54880021E549 /* Tracing.h */; };
1187
		5D5D8AD10E0D0EBE00F9C692 /* libedit.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D5D8AD00E0D0EBE00F9C692 /* libedit.dylib */; };
1193
		5D5D8AD10E0D0EBE00F9C692 /* libedit.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D5D8AD00E0D0EBE00F9C692 /* libedit.dylib */; };
1188
		5DBB151B131D0B310056AD36 /* testapi.js in Copy Support Script */ = {isa = PBXBuildFile; fileRef = 14D857740A4696C80032146C /* testapi.js */; };
1194
		5DBB151B131D0B310056AD36 /* testapi.js in Copy Support Script */ = {isa = PBXBuildFile; fileRef = 14D857740A4696C80032146C /* testapi.js */; };
Lines 3312-3317 a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec2
3312
		53F256E11B87E28000B4B768 /* JSTypedArrayViewPrototype.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSTypedArrayViewPrototype.cpp; sourceTree = "<group>"; };
3318
		53F256E11B87E28000B4B768 /* JSTypedArrayViewPrototype.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSTypedArrayViewPrototype.cpp; sourceTree = "<group>"; };
3313
		53F6BF6C1C3F060A00F41E5D /* InternalFunctionAllocationProfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InternalFunctionAllocationProfile.h; sourceTree = "<group>"; };
3319
		53F6BF6C1C3F060A00F41E5D /* InternalFunctionAllocationProfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InternalFunctionAllocationProfile.h; sourceTree = "<group>"; };
3314
		593D43CCA0BBE06D89C59707 /* MapDataInlines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MapDataInlines.h; sourceTree = "<group>"; };
3320
		593D43CCA0BBE06D89C59707 /* MapDataInlines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MapDataInlines.h; sourceTree = "<group>"; };
3321
		5BD3A0611CAE325700F84BA3 /* AsyncFunctionConstructor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AsyncFunctionConstructor.cpp; sourceTree = "<group>"; };
3322
		5BD3A0621CAE325700F84BA3 /* AsyncFunctionConstructor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AsyncFunctionConstructor.h; sourceTree = "<group>"; };
3323
		5BD3A0631CAE325700F84BA3 /* AsyncFunctionPrototype.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AsyncFunctionPrototype.cpp; sourceTree = "<group>"; };
3324
		5BD3A0641CAE325700F84BA3 /* AsyncFunctionPrototype.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AsyncFunctionPrototype.h; sourceTree = "<group>"; };
3325
		5BD3A0651CAE325700F84BA3 /* JSAsyncFunction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSAsyncFunction.cpp; sourceTree = "<group>"; };
3326
		5BD3A06D1CAE35BF00F84BA3 /* JSAsyncFunction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSAsyncFunction.h; sourceTree = "<group>"; };
3327
		5BF474881CB1C5DB0002BAD7 /* AsyncFunctionPrototype.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = AsyncFunctionPrototype.js; sourceTree = "<group>"; };
3315
		5D53726D0E1C546B0021E549 /* Tracing.d */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Tracing.d; sourceTree = "<group>"; };
3328
		5D53726D0E1C546B0021E549 /* Tracing.d */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Tracing.d; sourceTree = "<group>"; };
3316
		5D53726E0E1C54880021E549 /* Tracing.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Tracing.h; sourceTree = "<group>"; };
3329
		5D53726E0E1C54880021E549 /* Tracing.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Tracing.h; sourceTree = "<group>"; };
3317
		5D53727D0E1C55EC0021E549 /* TracingDtrace.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TracingDtrace.h; sourceTree = "<group>"; };
3330
		5D53727D0E1C55EC0021E549 /* TracingDtrace.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TracingDtrace.h; sourceTree = "<group>"; };
Lines 5473-5478 a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec3
5473
		7EF6E0BB0EB7A1EC0079AFAF /* runtime */ = {
5486
		7EF6E0BB0EB7A1EC0079AFAF /* runtime */ = {
5474
			isa = PBXGroup;
5487
			isa = PBXGroup;
5475
			children = (
5488
			children = (
5489
				5BD3A0611CAE325700F84BA3 /* AsyncFunctionConstructor.cpp */,
5490
				5BD3A0621CAE325700F84BA3 /* AsyncFunctionConstructor.h */,
5491
				5BD3A0631CAE325700F84BA3 /* AsyncFunctionPrototype.cpp */,
5492
				5BD3A0641CAE325700F84BA3 /* AsyncFunctionPrototype.h */,
5493
				5BD3A0651CAE325700F84BA3 /* JSAsyncFunction.cpp */,
5494
				5BD3A06D1CAE35BF00F84BA3 /* JSAsyncFunction.h */,
5476
				BCF605110E203EF800B9A64D /* ArgList.cpp */,
5495
				BCF605110E203EF800B9A64D /* ArgList.cpp */,
5477
				BCF605120E203EF800B9A64D /* ArgList.h */,
5496
				BCF605120E203EF800B9A64D /* ArgList.h */,
5478
				0FE0500C1AA9091100D33B33 /* ArgumentsMode.h */,
5497
				0FE0500C1AA9091100D33B33 /* ArgumentsMode.h */,
Lines 6815-6820 a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec4
6815
		A7D8019F1880D66E0026C39B /* builtins */ = {
6834
		A7D8019F1880D66E0026C39B /* builtins */ = {
6816
			isa = PBXGroup;
6835
			isa = PBXGroup;
6817
			children = (
6836
			children = (
6837
				5BF474881CB1C5DB0002BAD7 /* AsyncFunctionPrototype.js */,
6818
				A7D801A01880D66E0026C39B /* ArrayPrototype.js */,
6838
				A7D801A01880D66E0026C39B /* ArrayPrototype.js */,
6819
				7CF9BC581B65D9A3009DB1EF /* ArrayConstructor.js */,
6839
				7CF9BC581B65D9A3009DB1EF /* ArrayConstructor.js */,
6820
				7CF9BC591B65D9A3009DB1EF /* ArrayIteratorPrototype.js */,
6840
				7CF9BC591B65D9A3009DB1EF /* ArrayIteratorPrototype.js */,
Lines 7126-7131 a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec5
7126
				0F426A4B1460CD6E00131F8F /* DataFormat.h in Headers */,
7146
				0F426A4B1460CD6E00131F8F /* DataFormat.h in Headers */,
7127
				0F2B66DF17B6B5AB00A7AE3F /* DataView.h in Headers */,
7147
				0F2B66DF17B6B5AB00A7AE3F /* DataView.h in Headers */,
7128
				BCD2034A0E17135E002C7E82 /* DateConstructor.h in Headers */,
7148
				BCD2034A0E17135E002C7E82 /* DateConstructor.h in Headers */,
7149
				5BD3A0681CAE325700F84BA3 /* AsyncFunctionConstructor.h in Headers */,
7129
				996B731A1BDA08D100331B84 /* DateConstructor.lut.h in Headers */,
7150
				996B731A1BDA08D100331B84 /* DateConstructor.lut.h in Headers */,
7130
				41359CF30FDD89AD00206180 /* DateConversion.h in Headers */,
7151
				41359CF30FDD89AD00206180 /* DateConversion.h in Headers */,
7131
				BC1166020E1997B4008066DD /* DateInstance.h in Headers */,
7152
				BC1166020E1997B4008066DD /* DateInstance.h in Headers */,
Lines 7481-7486 a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec6
7481
				FE187A0D1C030D5C0038BBCA /* JITDivGenerator.h in Headers */,
7502
				FE187A0D1C030D5C0038BBCA /* JITDivGenerator.h in Headers */,
7482
				2AD8932B17E3868F00668276 /* HeapIterationScope.h in Headers */,
7503
				2AD8932B17E3868F00668276 /* HeapIterationScope.h in Headers */,
7483
				A5339EC91BB4B4600054F005 /* HeapObserver.h in Headers */,
7504
				A5339EC91BB4B4600054F005 /* HeapObserver.h in Headers */,
7505
				5BD3A06A1CAE325700F84BA3 /* AsyncFunctionPrototype.h in Headers */,
7484
				2A6F462617E959CE00C45C98 /* HeapOperation.h in Headers */,
7506
				2A6F462617E959CE00C45C98 /* HeapOperation.h in Headers */,
7485
				14F97447138C853E00DA1C67 /* HeapRootVisitor.h in Headers */,
7507
				14F97447138C853E00DA1C67 /* HeapRootVisitor.h in Headers */,
7486
				C24D31E3161CD695002AA4DB /* HeapStatistics.h in Headers */,
7508
				C24D31E3161CD695002AA4DB /* HeapStatistics.h in Headers */,
Lines 8020-8025 a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec7
8020
				A7B601821639FD2A00372BA3 /* UnlinkedCodeBlock.h in Headers */,
8042
				A7B601821639FD2A00372BA3 /* UnlinkedCodeBlock.h in Headers */,
8021
				14142E511B796ECE00F4BF4B /* UnlinkedFunctionExecutable.h in Headers */,
8043
				14142E511B796ECE00F4BF4B /* UnlinkedFunctionExecutable.h in Headers */,
8022
				0F2E892C16D028AD009E4FD2 /* UnusedPointer.h in Headers */,
8044
				0F2E892C16D028AD009E4FD2 /* UnusedPointer.h in Headers */,
8045
				5BD3A06E1CAE35BF00F84BA3 /* JSAsyncFunction.h in Headers */,
8023
				99DA00B11BD5994E00F4575C /* UpdateContents.py in Headers */,
8046
				99DA00B11BD5994E00F4575C /* UpdateContents.py in Headers */,
8024
				0F963B3813FC6FE90002D9B2 /* ValueProfile.h in Headers */,
8047
				0F963B3813FC6FE90002D9B2 /* ValueProfile.h in Headers */,
8025
				0F426A481460CBB300131F8F /* ValueRecovery.h in Headers */,
8048
				0F426A481460CBB300131F8F /* ValueRecovery.h in Headers */,
Lines 8603-8608 a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec8
8603
				0FEC858B1BDACDC70080FF74 /* AirStackSlot.cpp in Sources */,
8626
				0FEC858B1BDACDC70080FF74 /* AirStackSlot.cpp in Sources */,
8604
				0FEC858D1BDACDC70080FF74 /* AirTmp.cpp in Sources */,
8627
				0FEC858D1BDACDC70080FF74 /* AirTmp.cpp in Sources */,
8605
				0FEC85901BDACDC70080FF74 /* AirValidate.cpp in Sources */,
8628
				0FEC85901BDACDC70080FF74 /* AirValidate.cpp in Sources */,
8629
				5BD3A06B1CAE325700F84BA3 /* JSAsyncFunction.cpp in Sources */,
8606
				147F39BD107EC37600427A48 /* ArgList.cpp in Sources */,
8630
				147F39BD107EC37600427A48 /* ArgList.cpp in Sources */,
8607
				0F743BAA16B88249009F9277 /* ARM64Disassembler.cpp in Sources */,
8631
				0F743BAA16B88249009F9277 /* ARM64Disassembler.cpp in Sources */,
8608
				86D3B2C310156BDE002865E7 /* ARMAssembler.cpp in Sources */,
8632
				86D3B2C310156BDE002865E7 /* ARMAssembler.cpp in Sources */,
Lines 9213-9218 a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec9
9213
				0FF729AE166AD35C000F5BA3 /* ProfilerBytecodes.cpp in Sources */,
9237
				0FF729AE166AD35C000F5BA3 /* ProfilerBytecodes.cpp in Sources */,
9214
				0F13912916771C33009CCB07 /* ProfilerBytecodeSequence.cpp in Sources */,
9238
				0F13912916771C33009CCB07 /* ProfilerBytecodeSequence.cpp in Sources */,
9215
				0FF729AF166AD35C000F5BA3 /* ProfilerCompilation.cpp in Sources */,
9239
				0FF729AF166AD35C000F5BA3 /* ProfilerCompilation.cpp in Sources */,
9240
				5BD3A0671CAE325700F84BA3 /* AsyncFunctionConstructor.cpp in Sources */,
9216
				0FF729B0166AD35C000F5BA3 /* ProfilerCompilationKind.cpp in Sources */,
9241
				0FF729B0166AD35C000F5BA3 /* ProfilerCompilationKind.cpp in Sources */,
9217
				0FF729B1166AD35C000F5BA3 /* ProfilerCompiledBytecode.cpp in Sources */,
9242
				0FF729B1166AD35C000F5BA3 /* ProfilerCompiledBytecode.cpp in Sources */,
9218
				0FF729B2166AD35C000F5BA3 /* ProfilerDatabase.cpp in Sources */,
9243
				0FF729B2166AD35C000F5BA3 /* ProfilerDatabase.cpp in Sources */,
Lines 9346-9351 a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj_sec10
9346
				0F919D2515853CE0004A4E7D /* Watchpoint.cpp in Sources */,
9371
				0F919D2515853CE0004A4E7D /* Watchpoint.cpp in Sources */,
9347
				1ACF7377171CA6FB00C9BB1E /* Weak.cpp in Sources */,
9372
				1ACF7377171CA6FB00C9BB1E /* Weak.cpp in Sources */,
9348
				14E84F9E14EE1ACC00D6D5D4 /* WeakBlock.cpp in Sources */,
9373
				14E84F9E14EE1ACC00D6D5D4 /* WeakBlock.cpp in Sources */,
9374
				5BD3A0691CAE325700F84BA3 /* AsyncFunctionPrototype.cpp in Sources */,
9349
				14F7256514EE265E00B1652B /* WeakHandleOwner.cpp in Sources */,
9375
				14F7256514EE265E00B1652B /* WeakHandleOwner.cpp in Sources */,
9350
				A7CA3AE317DA41AE006538AF /* WeakMapConstructor.cpp in Sources */,
9376
				A7CA3AE317DA41AE006538AF /* WeakMapConstructor.cpp in Sources */,
9351
				0F338DF91BE96AA80013C88F /* B3CCallValue.cpp in Sources */,
9377
				0F338DF91BE96AA80013C88F /* B3CCallValue.cpp in Sources */,
- a/Source/JavaScriptCore/builtins/AsyncFunctionPrototype.js +56 lines
Line 0 a/Source/JavaScriptCore/builtins/AsyncFunctionPrototype.js_sec1
1
/*
2
 * Copyright (C) 2015 Caitlin Potter <caitp@igalia.com>.
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 * 1. Redistributions of source code must retain the above copyright
8
 *    notice, this list of conditions and the following disclaimer.
9
 * 2. Redistributions in binary form must reproduce the above copyright
10
 *    notice, this list of conditions and the following disclaimer in the
11
 *    documentation and/or other materials provided with the distribution.
12
 *
13
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24
 */
25
26
function asyncFunctionResume(generator, sentValue, resumeMode)
27
{
28
    "use strict";
29
    const Completed = -1;
30
    const Executing = -2;
31
32
    const NormalMode = 0;
33
    const ThrowMode = 2;
34
35
    let state = generator.@generatorState;
36
    let value = @undefined;
37
38
    if (state === Completed || (resumeMode !== NormalMode && resumeMode !== ThrowMode))
39
        throw new @TypeError("Async function illegally resumed");
40
41
    try {
42
        generator.@generatorState = Executing;
43
        value = generator.@generatorNext.@call(generator.@generatorThis, generator, state, sentValue, resumeMode);
44
        if (generator.@generatorState === Executing) {
45
            generator.@generatorState = Completed;
46
            return @Promise.@resolve(value);
47
        }
48
    } catch (error) {
49
        generator.@generatorState = Completed;
50
        return @Promise.@reject(error);
51
    }
52
53
    return @Promise.@resolve(value).@then(
54
        (value) => @asyncFunctionResume(generator, value, /* NormalMode */ 0),
55
        (error) => @asyncFunctionResume(generator, error, /* ThrowMode */ 2));
56
}
- a/Source/JavaScriptCore/bytecode/BytecodeList.json +2 lines
Lines 93-98 a/Source/JavaScriptCore/bytecode/BytecodeList.json_sec1
93
            { "name" : "op_new_func_exp", "length" : 4 },
93
            { "name" : "op_new_func_exp", "length" : 4 },
94
            { "name" : "op_new_generator_func", "length" : 4 },
94
            { "name" : "op_new_generator_func", "length" : 4 },
95
            { "name" : "op_new_generator_func_exp", "length" : 4 },
95
            { "name" : "op_new_generator_func_exp", "length" : 4 },
96
            { "name" : "op_new_async_func", "length" : 4 },
97
            { "name" : "op_new_async_func_exp", "length" : 4 },
96
            { "name" : "op_new_arrow_func_exp", "length" : 4 },
98
            { "name" : "op_new_arrow_func_exp", "length" : 4 },
97
            { "name" : "op_set_function_name", "length" : 3 },
99
            { "name" : "op_set_function_name", "length" : 3 },
98
            { "name" : "op_call", "length" : 9 },
100
            { "name" : "op_call", "length" : 9 },
- a/Source/JavaScriptCore/bytecode/BytecodeUseDef.h +4 lines
Lines 134-139 void computeUsesForBytecodeOffset( a/Source/JavaScriptCore/bytecode/BytecodeUseDef.h_sec1
134
    case op_get_property_enumerator:
134
    case op_get_property_enumerator:
135
    case op_get_enumerable_length:
135
    case op_get_enumerable_length:
136
    case op_new_func_exp:
136
    case op_new_func_exp:
137
    case op_new_async_func_exp:
137
    case op_new_generator_func_exp:
138
    case op_new_generator_func_exp:
138
    case op_new_arrow_func_exp:
139
    case op_new_arrow_func_exp:
139
    case op_to_index_string:
140
    case op_to_index_string:
Lines 163-168 void computeUsesForBytecodeOffset( a/Source/JavaScriptCore/bytecode/BytecodeUseDef.h_sec2
163
    case op_del_by_id:
164
    case op_del_by_id:
164
    case op_unsigned:
165
    case op_unsigned:
165
    case op_new_func:
166
    case op_new_func:
167
    case op_new_async_func:
166
    case op_new_generator_func:
168
    case op_new_generator_func:
167
    case op_get_parent_scope:
169
    case op_get_parent_scope:
168
    case op_create_scoped_arguments:
170
    case op_create_scoped_arguments:
Lines 352-357 void computeDefsForBytecodeOffset(CodeBlock* codeBlock, BytecodeBasicBlock* bloc a/Source/JavaScriptCore/bytecode/BytecodeUseDef.h_sec3
352
    case op_new_regexp:
354
    case op_new_regexp:
353
    case op_new_func:
355
    case op_new_func:
354
    case op_new_func_exp:
356
    case op_new_func_exp:
357
    case op_new_async_func:
358
    case op_new_async_func_exp:
355
    case op_new_generator_func:
359
    case op_new_generator_func:
356
    case op_new_generator_func_exp:
360
    case op_new_generator_func_exp:
357
    case op_new_arrow_func_exp:
361
    case op_new_arrow_func_exp:
- a/Source/JavaScriptCore/bytecode/CodeBlock.cpp -1 / +17 lines
Lines 1347-1352 void CodeBlock::dumpBytecode( a/Source/JavaScriptCore/bytecode/CodeBlock.cpp_sec1
1347
            out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1347
            out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1348
            break;
1348
            break;
1349
        }
1349
        }
1350
        case op_new_async_func: {
1351
            int r0 = (++it)->u.operand;
1352
            int r1 = (++it)->u.operand;
1353
            int f0 = (++it)->u.operand;
1354
            printLocationAndOp(out, exec, location, it, "new_async_func");
1355
            out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1356
            break;
1357
        }
1358
        case op_new_async_func_exp: {
1359
            int r0 = (++it)->u.operand;
1360
            int r1 = (++it)->u.operand;
1361
            int f0 = (++it)->u.operand;
1362
            printLocationAndOp(out, exec, location, it, "new_async_func_exp");
1363
            out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1364
            break;
1365
        }
1350
        case op_new_arrow_func_exp: {
1366
        case op_new_arrow_func_exp: {
1351
            int r0 = (++it)->u.operand;
1367
            int r0 = (++it)->u.operand;
1352
            int r1 = (++it)->u.operand;
1368
            int r1 = (++it)->u.operand;
Lines 2305-2311 void CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, Unlink a/Source/JavaScriptCore/bytecode/CodeBlock.cpp_sec2
2305
    m_instructions = WTFMove(instructions);
2321
    m_instructions = WTFMove(instructions);
2306
2322
2307
    // Perform bytecode liveness analysis to determine which locals are live and should be resumed when executing op_resume.
2323
    // Perform bytecode liveness analysis to determine which locals are live and should be resumed when executing op_resume.
2308
    if (unlinkedCodeBlock->parseMode() == SourceParseMode::GeneratorBodyMode) {
2324
    if (unlinkedCodeBlock->parseMode() == SourceParseMode::GeneratorBodyMode || isAsyncFunctionBodyParseMode(unlinkedCodeBlock->parseMode())) {
2309
        if (size_t count = mergePointBytecodeOffsets.size()) {
2325
        if (size_t count = mergePointBytecodeOffsets.size()) {
2310
            createRareDataIfNecessary();
2326
            createRareDataIfNecessary();
2311
            BytecodeLivenessAnalysis liveness(this);
2327
            BytecodeLivenessAnalysis liveness(this);
- a/Source/JavaScriptCore/bytecode/UnlinkedCodeBlock.h +1 lines
Lines 119-124 public: a/Source/JavaScriptCore/bytecode/UnlinkedCodeBlock.h_sec1
119
    bool usesEval() const { return m_usesEval; }
119
    bool usesEval() const { return m_usesEval; }
120
    SourceParseMode parseMode() const { return m_parseMode; }
120
    SourceParseMode parseMode() const { return m_parseMode; }
121
    bool isArrowFunction() const { return m_parseMode == SourceParseMode::ArrowFunctionMode; }
121
    bool isArrowFunction() const { return m_parseMode == SourceParseMode::ArrowFunctionMode; }
122
    bool isAsyncArrowFunction() const { return m_parseMode == SourceParseMode::AsyncArrowFunctionMode; }
122
    DerivedContextType derivedContextType() const { return static_cast<DerivedContextType>(m_derivedContextType); }
123
    DerivedContextType derivedContextType() const { return static_cast<DerivedContextType>(m_derivedContextType); }
123
    EvalContextType evalContextType() const { return static_cast<EvalContextType>(m_evalContextType); }
124
    EvalContextType evalContextType() const { return static_cast<EvalContextType>(m_evalContextType); }
124
    bool isArrowFunctionContext() const { return m_isArrowFunctionContext; }
125
    bool isArrowFunctionContext() const { return m_isArrowFunctionContext; }
- a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp -14 / +84 lines
Lines 32-37 a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec1
32
#include "BytecodeGenerator.h"
32
#include "BytecodeGenerator.h"
33
33
34
#include "BuiltinExecutables.h"
34
#include "BuiltinExecutables.h"
35
#include "BuiltinNames.h"
35
#include "BytecodeLivenessAnalysis.h"
36
#include "BytecodeLivenessAnalysis.h"
36
#include "Interpreter.h"
37
#include "Interpreter.h"
37
#include "JSFunction.h"
38
#include "JSFunction.h"
Lines 241-257 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, Unlinke a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec2
241
242
242
    SourceParseMode parseMode = codeBlock->parseMode();
243
    SourceParseMode parseMode = codeBlock->parseMode();
243
244
244
    bool containsArrowOrEvalButNotInArrowBlock = ((functionNode->usesArrowFunction() && functionNode->doAnyInnerArrowFunctionsUseAnyFeature()) || functionNode->usesEval()) && !m_codeBlock->isArrowFunction();
245
    bool containsArrowOrEvalButNotInArrowBlock = ((functionNode->usesArrowFunction() && functionNode->doAnyInnerArrowFunctionsUseAnyFeature()) || functionNode->usesEval()) && (!m_codeBlock->isArrowFunction() && !m_codeBlock->isAsyncArrowFunction());
245
    bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || functionNode->needsActivation() || containsArrowOrEvalButNotInArrowBlock;
246
    bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || functionNode->needsActivation() || containsArrowOrEvalButNotInArrowBlock;
246
247
247
    bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
248
    bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
248
    bool needsArguments = (functionNode->usesArguments() || codeBlock->usesEval() || (functionNode->usesArrowFunction() && !codeBlock->isArrowFunction() && isArgumentsUsedInInnerArrowFunction()));
249
    bool needsArguments = (functionNode->usesArguments() || codeBlock->usesEval() || (functionNode->usesArrowFunction() && !codeBlock->isArrowFunction() && !codeBlock->isAsyncArrowFunction() && isArgumentsUsedInInnerArrowFunction()));
249
250
250
    // Generator never provides "arguments". "arguments" reference will be resolved in an upper generator function scope.
251
    // Generator and AsyncFunction never provides "arguments". "arguments" reference will be resolved in an upper generator function scope.
251
    if (parseMode == SourceParseMode::GeneratorBodyMode)
252
    if (parseMode == SourceParseMode::GeneratorBodyMode || isAsyncFunctionBodyParseMode(parseMode))
252
        needsArguments = false;
253
        needsArguments = false;
253
254
254
    if (parseMode == SourceParseMode::GeneratorWrapperFunctionMode && needsArguments) {
255
    if ((parseMode == SourceParseMode::GeneratorWrapperFunctionMode || isAsyncFunctionWrapperParseMode(parseMode)) && needsArguments) {
255
        // Generator does not provide "arguments". Instead, wrapping GeneratorFunction provides "arguments".
256
        // Generator does not provide "arguments". Instead, wrapping GeneratorFunction provides "arguments".
256
        // This is because arguments of a generator should be evaluated before starting it.
257
        // This is because arguments of a generator should be evaluated before starting it.
257
        // To workaround it, we evaluate these arguments as arguments of a wrapping generator function, and reference it from a generator.
258
        // To workaround it, we evaluate these arguments as arguments of a wrapping generator function, and reference it from a generator.
Lines 298-304 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, Unlinke a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec3
298
    ASSERT(!(isSimpleParameterList && m_restParameter));
299
    ASSERT(!(isSimpleParameterList && m_restParameter));
299
300
300
    // Before emitting a scope creation, emit a generator prologue that contains jump based on a generator's state.
301
    // Before emitting a scope creation, emit a generator prologue that contains jump based on a generator's state.
301
    if (parseMode == SourceParseMode::GeneratorBodyMode) {
302
    if (parseMode == SourceParseMode::GeneratorBodyMode || isAsyncFunctionBodyParseMode(parseMode)) {
302
        m_generatorRegister = &m_parameters[1];
303
        m_generatorRegister = &m_parameters[1];
303
304
304
        // Jump with switch_imm based on @generatorState. We don't take the coroutine styled generator implementation.
305
        // Jump with switch_imm based on @generatorState. We don't take the coroutine styled generator implementation.
Lines 313-318 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, Unlinke a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec4
313
314
314
    if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())) {
315
    if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())) {
315
        ASSERT(parseMode != SourceParseMode::GeneratorBodyMode);
316
        ASSERT(parseMode != SourceParseMode::GeneratorBodyMode);
317
        ASSERT(parseMode != SourceParseMode::AsyncFunctionBodyMode);
318
        ASSERT(parseMode != SourceParseMode::AsyncArrowFunctionBodyMode);
316
        bool isDynamicScope = functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode());
319
        bool isDynamicScope = functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode());
317
        bool isFunctionNameCaptured = captures(functionNode->ident().impl());
320
        bool isFunctionNameCaptured = captures(functionNode->ident().impl());
318
        bool markAsCaptured = isDynamicScope || isFunctionNameCaptured;
321
        bool markAsCaptured = isDynamicScope || isFunctionNameCaptured;
Lines 501-507 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, Unlinke a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec5
501
        }
504
        }
502
505
503
        // Do not create arguments variable in case of Arrow function. Value will be loaded from parent scope
506
        // Do not create arguments variable in case of Arrow function. Value will be loaded from parent scope
504
        if (!haveParameterNamedArguments && !m_codeBlock->isArrowFunction()) {
507
        if (!haveParameterNamedArguments && !m_codeBlock->isArrowFunction() && !m_codeBlock->isAsyncArrowFunction()) {
505
            createVariable(
508
            createVariable(
506
                propertyNames().arguments, varKind(propertyNames().arguments.impl()), functionSymbolTable);
509
                propertyNames().arguments, varKind(propertyNames().arguments.impl()), functionSymbolTable);
507
510
Lines 527-532 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, Unlinke a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec6
527
        break;
530
        break;
528
    }
531
    }
529
532
533
    case SourceParseMode::AsyncArrowFunctionMode:
534
    case SourceParseMode::AsyncMethodMode:
535
    case SourceParseMode::AsyncFunctionMode: {
536
        ASSERT(!isConstructor());
537
        ASSERT(constructorKind() == ConstructorKind::None);
538
        m_generatorRegister = addVar();
539
540
        if (parseMode != SourceParseMode::AsyncArrowFunctionMode) {
541
            if (functionNode->usesThis() || codeBlock->usesEval()) {
542
                m_codeBlock->addPropertyAccessInstruction(instructions().size());
543
                emitOpcode(op_to_this);
544
                instructions().append(kill(&m_thisRegister));
545
                instructions().append(0);
546
                instructions().append(0);
547
            }
548
549
            emitMove(m_generatorRegister, &m_calleeRegister);
550
            emitCreateThis(m_generatorRegister);
551
        } else
552
            emitMove(m_generatorRegister, &m_calleeRegister);
553
        break;
554
    }
555
556
    case SourceParseMode::AsyncFunctionBodyMode:
557
    case SourceParseMode::AsyncArrowFunctionBodyMode:
530
    case SourceParseMode::GeneratorBodyMode: {
558
    case SourceParseMode::GeneratorBodyMode: {
531
        // |this| is already filled correctly before here.
559
        // |this| is already filled correctly before here.
532
        emitLoad(m_newTargetRegister, jsUndefined());
560
        emitLoad(m_newTargetRegister, jsUndefined());
Lines 558-577 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, Unlinke a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec7
558
    // All "addVar()"s needs to happen before "initializeDefaultParameterValuesAndSetupFunctionScopeStack()" is called
586
    // All "addVar()"s needs to happen before "initializeDefaultParameterValuesAndSetupFunctionScopeStack()" is called
559
    // because a function's default parameter ExpressionNodes will use temporary registers.
587
    // because a function's default parameter ExpressionNodes will use temporary registers.
560
    pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize);
588
    pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize);
589
590
    TryData* tryFormalParametersData = nullptr;
591
    if (isAsyncFunctionWrapperParseMode(parseMode)) {
592
        RefPtr<Label> tryFormalParametersStart = emitLabel(newLabel().get());
593
        tryFormalParametersData = pushTry(tryFormalParametersStart.get());
594
    }
595
561
    initializeDefaultParameterValuesAndSetupFunctionScopeStack(parameters, isSimpleParameterList, functionNode, functionSymbolTable, symbolTableConstantIndex, captures);
596
    initializeDefaultParameterValuesAndSetupFunctionScopeStack(parameters, isSimpleParameterList, functionNode, functionSymbolTable, symbolTableConstantIndex, captures);
562
    
597
598
    if (isAsyncFunctionWrapperParseMode(parseMode)) {
599
        RefPtr<Label> didNotThrow = newLabel();
600
        emitJump(didNotThrow.get());
601
        RefPtr<RegisterID> exception = newTemporary();
602
        RefPtr<RegisterID> thrownValue = newTemporary();
603
        RefPtr<Label> catchHere = emitLabel(newLabel().get());
604
        popTryAndEmitCatch(tryFormalParametersData, exception.get(), thrownValue.get(), catchHere.get(), HandlerType::Catch);
605
606
        // return @Promise.@reject(thrownValue);
607
        Variable promiseVar = variable(m_vm->propertyNames->PromisePrivateName);
608
        RefPtr<RegisterID> scope = emitResolveScope(newTemporary(), promiseVar);
609
        RefPtr<RegisterID> promiseConstructor = emitGetFromScope(newTemporary(), scope.get(), promiseVar, ResolveMode::ThrowIfNotFound);
610
        RefPtr<RegisterID> promiseReject = emitGetById(newTemporary(), promiseConstructor.get(), m_vm->propertyNames->builtinNames().rejectPrivateName());
611
612
        CallArguments args(*this, nullptr, 1);
613
614
        emitMove(args.thisRegister(), promiseConstructor.get());
615
        emitMove(args.argumentRegister(0), thrownValue.get());
616
617
        JSTextPosition divot(functionNode->firstLine(), functionNode->startOffset(), functionNode->lineStartOffset());
618
619
        RefPtr<RegisterID> result = emitCall(newTemporary(), promiseReject.get(), NoExpectedFunction, args, divot, divot, divot);
620
        emitReturn(result.get());
621
622
        emitLabel(didNotThrow.get());
623
    }
624
563
    // Loading |this| inside an arrow function must be done after initializeDefaultParameterValuesAndSetupFunctionScopeStack()
625
    // Loading |this| inside an arrow function must be done after initializeDefaultParameterValuesAndSetupFunctionScopeStack()
564
    // because that function sets up the SymbolTable stack and emitLoadThisFromArrowFunctionLexicalEnvironment()
626
    // because that function sets up the SymbolTable stack and emitLoadThisFromArrowFunctionLexicalEnvironment()
565
    // consults the SymbolTable stack
627
    // consults the SymbolTable stack
566
    if (SourceParseMode::ArrowFunctionMode == parseMode) {
628
    if (SourceParseMode::ArrowFunctionMode == parseMode || SourceParseMode::AsyncArrowFunctionBodyMode == parseMode || SourceParseMode::AsyncArrowFunctionMode == parseMode || SourceParseMode::AsyncArrowFunctionMode == parseMode) {
567
        if (functionNode->usesThis() || functionNode->usesSuperProperty())
629
        if (functionNode->usesThis() || functionNode->usesSuperProperty() || isSuperUsedInInnerArrowFunction())
568
            emitLoadThisFromArrowFunctionLexicalEnvironment();
630
            emitLoadThisFromArrowFunctionLexicalEnvironment();
569
    
631
    
570
        if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
632
        if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
571
            emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
633
            emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
572
    }
634
    }
573
    
635
    
574
    if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunction()) {
636
    if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunction() && !codeBlock->isAsyncArrowFunction()) {
575
        initializeArrowFunctionContextScopeIfNeeded(functionSymbolTable);
637
        initializeArrowFunctionContextScopeIfNeeded(functionSymbolTable);
576
        emitPutThisToArrowFunctionContextScope();
638
        emitPutThisToArrowFunctionContextScope();
577
        emitPutNewTargetToArrowFunctionContextScope();
639
        emitPutNewTargetToArrowFunctionContextScope();
Lines 2773-2778 void BytecodeGenerator::emitNewFunctionExpressionCommon(RegisterID* dst, Functio a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec8
2773
    default: {
2835
    default: {
2774
        break;
2836
        break;
2775
    }
2837
    }
2838
    case SourceParseMode::AsyncFunctionMode:
2839
    case SourceParseMode::AsyncMethodMode:
2840
    case SourceParseMode::AsyncArrowFunctionMode:
2841
        opcodeID = op_new_async_func_exp;
2842
        break;
2776
    }
2843
    }
2777
    
2844
    
2778
    emitOpcode(opcodeID);
2845
    emitOpcode(opcodeID);
Lines 2789-2795 RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* dst, FuncEx a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec9
2789
2856
2790
RegisterID* BytecodeGenerator::emitNewArrowFunctionExpression(RegisterID* dst, ArrowFuncExprNode* func)
2857
RegisterID* BytecodeGenerator::emitNewArrowFunctionExpression(RegisterID* dst, ArrowFuncExprNode* func)
2791
{
2858
{
2792
    ASSERT(func->metadata()->parseMode() == SourceParseMode::ArrowFunctionMode);
2859
    ASSERT(func->metadata()->parseMode() == SourceParseMode::ArrowFunctionMode || func->metadata()->parseMode() == SourceParseMode::AsyncArrowFunctionMode);
2793
    emitNewFunctionExpressionCommon(dst, func->metadata());
2860
    emitNewFunctionExpressionCommon(dst, func->metadata());
2794
    return dst;
2861
    return dst;
2795
}
2862
}
Lines 2799-2805 RegisterID* BytecodeGenerator::emitNewMethodDefinition(RegisterID* dst, MethodDe a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec10
2799
    ASSERT(func->metadata()->parseMode() == SourceParseMode::GeneratorWrapperFunctionMode
2866
    ASSERT(func->metadata()->parseMode() == SourceParseMode::GeneratorWrapperFunctionMode
2800
        || func->metadata()->parseMode() == SourceParseMode::GetterMode
2867
        || func->metadata()->parseMode() == SourceParseMode::GetterMode
2801
        || func->metadata()->parseMode() == SourceParseMode::SetterMode
2868
        || func->metadata()->parseMode() == SourceParseMode::SetterMode
2802
        || func->metadata()->parseMode() == SourceParseMode::MethodMode);
2869
        || func->metadata()->parseMode() == SourceParseMode::MethodMode
2870
        || func->metadata()->parseMode() == SourceParseMode::AsyncMethodMode);
2803
    emitNewFunctionExpressionCommon(dst, func->metadata());
2871
    emitNewFunctionExpressionCommon(dst, func->metadata());
2804
    return dst;
2872
    return dst;
2805
}
2873
}
Lines 2826-2831 RegisterID* BytecodeGenerator::emitNewFunction(RegisterID* dst, FunctionMetadata a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec11
2826
    unsigned index = m_codeBlock->addFunctionDecl(makeFunction(function));
2894
    unsigned index = m_codeBlock->addFunctionDecl(makeFunction(function));
2827
    if (function->parseMode() == SourceParseMode::GeneratorWrapperFunctionMode)
2895
    if (function->parseMode() == SourceParseMode::GeneratorWrapperFunctionMode)
2828
        emitOpcode(op_new_generator_func);
2896
        emitOpcode(op_new_generator_func);
2897
    else if (function->parseMode() == SourceParseMode::AsyncFunctionMode)
2898
        emitOpcode(op_new_async_func);
2829
    else
2899
    else
2830
        emitOpcode(op_new_func);
2900
        emitOpcode(op_new_func);
2831
    instructions().append(dst->index());
2901
    instructions().append(dst->index());
Lines 4116-4122 void BytecodeGenerator::popIndexedForInScope(RegisterID* localRegister) a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp_sec12
4116
4186
4117
RegisterID* BytecodeGenerator::emitLoadArrowFunctionLexicalEnvironment(const Identifier& identifier)
4187
RegisterID* BytecodeGenerator::emitLoadArrowFunctionLexicalEnvironment(const Identifier& identifier)
4118
{
4188
{
4119
    ASSERT(m_codeBlock->isArrowFunction() || m_codeBlock->isArrowFunctionContext() || constructorKind() == ConstructorKind::Derived || m_codeType == EvalCode);
4189
    ASSERT(m_codeBlock->isArrowFunction() || parseMode() == SourceParseMode::AsyncArrowFunctionBodyMode || parseMode() == SourceParseMode::AsyncArrowFunctionMode || m_codeBlock->isArrowFunctionContext() || constructorKind() == ConstructorKind::Derived || m_codeType == EvalCode);
4120
4190
4121
    return emitResolveScope(nullptr, variable(identifier, ThisResolutionType::Scoped));
4191
    return emitResolveScope(nullptr, variable(identifier, ThisResolutionType::Scoped));
4122
}
4192
}
- a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h -2 / +2 lines
Lines 809-815 namespace JSC { a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h_sec1
809
        {
809
        {
810
            DerivedContextType newDerivedContextType = DerivedContextType::None;
810
            DerivedContextType newDerivedContextType = DerivedContextType::None;
811
811
812
            if (metadata->parseMode() == SourceParseMode::ArrowFunctionMode) {
812
            if (metadata->parseMode() == SourceParseMode::ArrowFunctionMode || metadata->parseMode() == SourceParseMode::AsyncArrowFunctionMode) {
813
                if (constructorKind() == ConstructorKind::Derived || isDerivedConstructorContext())
813
                if (constructorKind() == ConstructorKind::Derived || isDerivedConstructorContext())
814
                    newDerivedContextType = DerivedContextType::DerivedConstructorContext;
814
                    newDerivedContextType = DerivedContextType::DerivedConstructorContext;
815
                else if (m_codeBlock->isClassContext() || isDerivedClassContext())
815
                else if (m_codeBlock->isClassContext() || isDerivedClassContext())
Lines 823-829 namespace JSC { a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h_sec2
823
            // https://bugs.webkit.org/show_bug.cgi?id=151547
823
            // https://bugs.webkit.org/show_bug.cgi?id=151547
824
            SourceParseMode parseMode = metadata->parseMode();
824
            SourceParseMode parseMode = metadata->parseMode();
825
            ConstructAbility constructAbility = ConstructAbility::CanConstruct;
825
            ConstructAbility constructAbility = ConstructAbility::CanConstruct;
826
            if (parseMode == SourceParseMode::GetterMode || parseMode == SourceParseMode::SetterMode || parseMode == SourceParseMode::ArrowFunctionMode || parseMode == SourceParseMode::GeneratorWrapperFunctionMode)
826
            if (parseMode == SourceParseMode::GetterMode || parseMode == SourceParseMode::SetterMode || parseMode == SourceParseMode::ArrowFunctionMode || parseMode == SourceParseMode::GeneratorWrapperFunctionMode || isAsyncFunctionParseMode(parseMode))
827
                constructAbility = ConstructAbility::CannotConstruct;
827
                constructAbility = ConstructAbility::CannotConstruct;
828
            else if (parseMode == SourceParseMode::MethodMode && metadata->constructorKind() == ConstructorKind::None)
828
            else if (parseMode == SourceParseMode::MethodMode && metadata->constructorKind() == ConstructorKind::None)
829
                constructAbility = ConstructAbility::CannotConstruct;
829
                constructAbility = ConstructAbility::CannotConstruct;
- a/Source/JavaScriptCore/bytecompiler/NodesCodegen.cpp +61 lines
Lines 3098-3103 void FunctionNode::emitBytecode(BytecodeGenerator& generator, RegisterID*) a/Source/JavaScriptCore/bytecompiler/NodesCodegen.cpp_sec1
3098
        break;
3098
        break;
3099
    }
3099
    }
3100
3100
3101
    case SourceParseMode::AsyncFunctionMode:
3102
    case SourceParseMode::AsyncMethodMode:
3103
    case SourceParseMode::AsyncArrowFunctionMode: {
3104
        StatementNode* singleStatement = this->singleStatement();
3105
        ASSERT(singleStatement->isExprStatement());
3106
        ExprStatementNode* exprStatement = static_cast<ExprStatementNode*>(singleStatement);
3107
        ExpressionNode* expr = exprStatement->expr();
3108
        ASSERT(expr->isFuncExprNode());
3109
        FuncExprNode* funcExpr = static_cast<FuncExprNode*>(expr);
3110
3111
        RefPtr<RegisterID> next = generator.newTemporary();
3112
        generator.emitNode(next.get(), funcExpr);
3113
3114
        if (generator.superBinding() == SuperBinding::Needed || generator.parseMode() == SourceParseMode::AsyncArrowFunctionMode) {
3115
            // FIXME: Don't always load home object for async arrows
3116
            RefPtr<RegisterID> homeObject = emitHomeObjectForCallee(generator);
3117
            emitPutHomeObject(generator, next.get(), homeObject.get());
3118
        }
3119
3120
        // FIXME: Currently, we just create an object and store generator related fields as its properties for ease.
3121
        // But to make it efficient, we will introduce JSGenerator class, add opcode new_generator and use its C++ fields instead of these private properties.
3122
        // https://bugs.webkit.org/show_bug.cgi?id=151545
3123
3124
        generator.emitDirectPutById(generator.generatorRegister(), generator.propertyNames().generatorNextPrivateName, next.get(), PropertyNode::KnownDirect);
3125
3126
        generator.emitDirectPutById(generator.generatorRegister(), generator.propertyNames().generatorThisPrivateName, generator.thisRegister(), PropertyNode::KnownDirect);
3127
3128
        RegisterID* initialState = generator.emitLoad(nullptr, jsNumber(0));
3129
        generator.emitDirectPutById(generator.generatorRegister(), generator.propertyNames().generatorStatePrivateName, initialState, PropertyNode::KnownDirect);
3130
3131
        generator.emitDirectPutById(generator.generatorRegister(), generator.propertyNames().generatorFramePrivateName, generator.emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
3132
3133
        ASSERT(startOffset() >= lineStartOffset());
3134
        generator.emitDebugHook(WillLeaveCallFrame, lastLine(), startOffset(), lineStartOffset());
3135
3136
        // load @asyncFunctionResume, and call.
3137
        RefPtr<RegisterID> startAsyncFunction = generator.newTemporary();
3138
        auto var = generator.variable(generator.propertyNames().builtinNames().asyncFunctionResumePrivateName());
3139
3140
        RefPtr<RegisterID> scope = generator.newTemporary();
3141
        generator.moveToDestinationIfNeeded(scope.get(), generator.emitResolveScope(scope.get(), var));
3142
        generator.emitGetFromScope(startAsyncFunction.get(), scope.get(), var, ThrowIfNotFound);
3143
3144
        // return @asyncFunctionResume.@call(this, @generator, @undefined, GeneratorResumeMode::NormalMode)
3145
        CallArguments args(generator, nullptr, 3);
3146
        unsigned argumentCount = 0;
3147
        generator.emitLoad(args.thisRegister(), jsUndefined());
3148
        generator.emitMove(args.argumentRegister(argumentCount++), generator.generatorRegister());
3149
        generator.emitLoad(args.argumentRegister(argumentCount++), jsUndefined());
3150
        generator.emitLoad(args.argumentRegister(argumentCount++), jsNumber(static_cast<int32_t>(JSGeneratorFunction::GeneratorResumeMode::NormalMode)));
3151
        // JSTextPosition(int _line, int _offset, int _lineStartOffset)
3152
        JSTextPosition divot(firstLine(), startOffset(), lineStartOffset());
3153
3154
        RefPtr<RegisterID> result = generator.newTemporary();
3155
        generator.emitCall(result.get(), startAsyncFunction.get(), NoExpectedFunction, args, divot, divot, divot);
3156
        generator.emitReturn(result.get());
3157
        break;
3158
    }
3159
3160
    case SourceParseMode::AsyncArrowFunctionBodyMode:
3161
    case SourceParseMode::AsyncFunctionBodyMode:
3101
    case SourceParseMode::GeneratorBodyMode: {
3162
    case SourceParseMode::GeneratorBodyMode: {
3102
        RefPtr<Label> generatorBodyLabel = generator.newLabel();
3163
        RefPtr<Label> generatorBodyLabel = generator.newLabel();
3103
        {
3164
        {
- a/Source/JavaScriptCore/jit/JIT.cpp +2 lines
Lines 269-274 void JIT::privateCompileMainPass() a/Source/JavaScriptCore/jit/JIT.cpp_sec1
269
        DEFINE_OP(op_new_func_exp)
269
        DEFINE_OP(op_new_func_exp)
270
        DEFINE_OP(op_new_generator_func)
270
        DEFINE_OP(op_new_generator_func)
271
        DEFINE_OP(op_new_generator_func_exp)
271
        DEFINE_OP(op_new_generator_func_exp)
272
        DEFINE_OP(op_new_async_func)
273
        DEFINE_OP(op_new_async_func_exp)
272
        DEFINE_OP(op_new_arrow_func_exp) 
274
        DEFINE_OP(op_new_arrow_func_exp) 
273
        DEFINE_OP(op_new_object)
275
        DEFINE_OP(op_new_object)
274
        DEFINE_OP(op_new_regexp)
276
        DEFINE_OP(op_new_regexp)
- a/Source/JavaScriptCore/jit/JIT.h +2 lines
Lines 545-550 namespace JSC { a/Source/JavaScriptCore/jit/JIT.h_sec1
545
        void emit_op_new_func_exp(Instruction*);
545
        void emit_op_new_func_exp(Instruction*);
546
        void emit_op_new_generator_func(Instruction*);
546
        void emit_op_new_generator_func(Instruction*);
547
        void emit_op_new_generator_func_exp(Instruction*);
547
        void emit_op_new_generator_func_exp(Instruction*);
548
        void emit_op_new_async_func(Instruction*);
549
        void emit_op_new_async_func_exp(Instruction*);
548
        void emit_op_new_arrow_func_exp(Instruction*);
550
        void emit_op_new_arrow_func_exp(Instruction*);
549
        void emit_op_new_object(Instruction*);
551
        void emit_op_new_object(Instruction*);
550
        void emit_op_new_regexp(Instruction*);
552
        void emit_op_new_regexp(Instruction*);
- a/Source/JavaScriptCore/jit/JITOpcodes.cpp +13 lines
Lines 991-996 void JIT::emit_op_new_generator_func(Instruction* currentInstruction) a/Source/JavaScriptCore/jit/JITOpcodes.cpp_sec1
991
    emitNewFuncCommon(currentInstruction);
991
    emitNewFuncCommon(currentInstruction);
992
}
992
}
993
993
994
void JIT::emit_op_new_async_func(Instruction* currentInstruction)
995
{
996
    emitNewFuncCommon(currentInstruction);
997
}
998
994
void JIT::emitNewFuncExprCommon(Instruction* currentInstruction)
999
void JIT::emitNewFuncExprCommon(Instruction* currentInstruction)
995
{
1000
{
996
    Jump notUndefinedScope;
1001
    Jump notUndefinedScope;
Lines 1012-1017 void JIT::emitNewFuncExprCommon(Instruction* currentInstruction) a/Source/JavaScriptCore/jit/JITOpcodes.cpp_sec2
1012
1017
1013
    if (opcodeID == op_new_func_exp || opcodeID == op_new_arrow_func_exp)
1018
    if (opcodeID == op_new_func_exp || opcodeID == op_new_arrow_func_exp)
1014
        callOperation(operationNewFunction, dst, regT0, function);
1019
        callOperation(operationNewFunction, dst, regT0, function);
1020
    else if (opcodeID == op_new_async_func_exp)
1021
        callOperation(operationNewAsyncFunction, dst, regT0, function);
1015
    else {
1022
    else {
1016
        ASSERT(opcodeID == op_new_generator_func_exp);
1023
        ASSERT(opcodeID == op_new_generator_func_exp);
1017
        callOperation(operationNewGeneratorFunction, dst, regT0, function);
1024
        callOperation(operationNewGeneratorFunction, dst, regT0, function);
Lines 1030-1035 void JIT::emit_op_new_generator_func_exp(Instruction* currentInstruction) a/Source/JavaScriptCore/jit/JITOpcodes.cpp_sec3
1030
    emitNewFuncExprCommon(currentInstruction);
1037
    emitNewFuncExprCommon(currentInstruction);
1031
}
1038
}
1032
1039
1040
void JIT::emit_op_new_async_func_exp(Instruction* currentInstruction)
1041
{
1042
    emitNewFuncExprCommon(currentInstruction);
1043
}
1044
1045
1033
void JIT::emit_op_new_arrow_func_exp(Instruction* currentInstruction)
1046
void JIT::emit_op_new_arrow_func_exp(Instruction* currentInstruction)
1034
{
1047
{
1035
    emitNewFuncExprCommon(currentInstruction);
1048
    emitNewFuncExprCommon(currentInstruction);
- a/Source/JavaScriptCore/jit/JITOperations.cpp +11 lines
Lines 45-50 a/Source/JavaScriptCore/jit/JITOperations.cpp_sec1
45
#include "JIT.h"
45
#include "JIT.h"
46
#include "JITExceptions.h"
46
#include "JITExceptions.h"
47
#include "JITToDFGDeferredCompilationCallback.h"
47
#include "JITToDFGDeferredCompilationCallback.h"
48
#include "JSAsyncFunction.h"
48
#include "JSCInlines.h"
49
#include "JSCInlines.h"
49
#include "JSGeneratorFunction.h"
50
#include "JSGeneratorFunction.h"
50
#include "JSGlobalObjectFunctions.h"
51
#include "JSGlobalObjectFunctions.h"
Lines 1008-1013 EncodedJSValue JIT_OPERATION operationNewFunctionWithInvalidatedReallocationWatc a/Source/JavaScriptCore/jit/JITOperations.cpp_sec2
1008
    return operationNewFunctionCommon<JSFunction>(exec, scope, functionExecutable, true);
1009
    return operationNewFunctionCommon<JSFunction>(exec, scope, functionExecutable, true);
1009
}
1010
}
1010
1011
1012
EncodedJSValue JIT_OPERATION operationNewAsyncFunction(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1013
{
1014
    return operationNewFunctionCommon<JSAsyncFunction>(exec, scope, functionExecutable, false);
1015
}
1016
1017
EncodedJSValue JIT_OPERATION operationNewAsyncFunctionWithInvalidatedReallocationWatchpoint(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1018
{
1019
    return operationNewFunctionCommon<JSAsyncFunction>(exec, scope, functionExecutable, true);
1020
}
1021
1011
EncodedJSValue JIT_OPERATION operationNewGeneratorFunction(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1022
EncodedJSValue JIT_OPERATION operationNewGeneratorFunction(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1012
{
1023
{
1013
    return operationNewFunctionCommon<JSGeneratorFunction>(exec, scope, functionExecutable, false);
1024
    return operationNewFunctionCommon<JSGeneratorFunction>(exec, scope, functionExecutable, false);
- a/Source/JavaScriptCore/jit/JITOperations.h +2 lines
Lines 332-337 EncodedJSValue JIT_OPERATION operationNewArrayBufferWithProfile(ExecState*, Arra a/Source/JavaScriptCore/jit/JITOperations.h_sec1
332
EncodedJSValue JIT_OPERATION operationNewArrayWithSizeAndProfile(ExecState*, ArrayAllocationProfile*, EncodedJSValue size) WTF_INTERNAL;
332
EncodedJSValue JIT_OPERATION operationNewArrayWithSizeAndProfile(ExecState*, ArrayAllocationProfile*, EncodedJSValue size) WTF_INTERNAL;
333
EncodedJSValue JIT_OPERATION operationNewFunction(ExecState*, JSScope*, JSCell*) WTF_INTERNAL;
333
EncodedJSValue JIT_OPERATION operationNewFunction(ExecState*, JSScope*, JSCell*) WTF_INTERNAL;
334
EncodedJSValue JIT_OPERATION operationNewFunctionWithInvalidatedReallocationWatchpoint(ExecState*, JSScope*, JSCell*) WTF_INTERNAL;
334
EncodedJSValue JIT_OPERATION operationNewFunctionWithInvalidatedReallocationWatchpoint(ExecState*, JSScope*, JSCell*) WTF_INTERNAL;
335
EncodedJSValue JIT_OPERATION operationNewAsyncFunction(ExecState*, JSScope*, JSCell*) WTF_INTERNAL;
336
EncodedJSValue JIT_OPERATION operationNewAsyncFunctionWithInvalidatedReallocationWatchpoint(ExecState*, JSScope*, JSCell*) WTF_INTERNAL;
335
EncodedJSValue JIT_OPERATION operationNewGeneratorFunction(ExecState*, JSScope*, JSCell*) WTF_INTERNAL;
337
EncodedJSValue JIT_OPERATION operationNewGeneratorFunction(ExecState*, JSScope*, JSCell*) WTF_INTERNAL;
336
EncodedJSValue JIT_OPERATION operationNewGeneratorFunctionWithInvalidatedReallocationWatchpoint(ExecState*, JSScope*, JSCell*) WTF_INTERNAL;
338
EncodedJSValue JIT_OPERATION operationNewGeneratorFunctionWithInvalidatedReallocationWatchpoint(ExecState*, JSScope*, JSCell*) WTF_INTERNAL;
337
void JIT_OPERATION operationSetFunctionName(ExecState*, JSCell*, EncodedJSValue) WTF_INTERNAL;
339
void JIT_OPERATION operationSetFunctionName(ExecState*, JSCell*, EncodedJSValue) WTF_INTERNAL;
- a/Source/JavaScriptCore/llint/LLIntSlowPaths.cpp +23 lines
Lines 39-44 a/Source/JavaScriptCore/llint/LLIntSlowPaths.cpp_sec1
39
#include "Interpreter.h"
39
#include "Interpreter.h"
40
#include "JIT.h"
40
#include "JIT.h"
41
#include "JITExceptions.h"
41
#include "JITExceptions.h"
42
#include "JSAsyncFunction.h"
42
#include "JSLexicalEnvironment.h"
43
#include "JSLexicalEnvironment.h"
43
#include "JSCInlines.h"
44
#include "JSCInlines.h"
44
#include "JSCJSValue.h"
45
#include "JSCJSValue.h"
Lines 1039-1044 LLINT_SLOW_PATH_DECL(slow_path_new_func) a/Source/JavaScriptCore/llint/LLIntSlowPaths.cpp_sec2
1039
    LLINT_RETURN(JSFunction::create(vm, codeBlock->functionDecl(pc[3].u.operand), scope));
1040
    LLINT_RETURN(JSFunction::create(vm, codeBlock->functionDecl(pc[3].u.operand), scope));
1040
}
1041
}
1041
1042
1043
LLINT_SLOW_PATH_DECL(slow_path_new_async_func)
1044
{
1045
    LLINT_BEGIN();
1046
    CodeBlock* codeBlock = exec->codeBlock();
1047
    JSScope* scope = exec->uncheckedR(pc[2].u.operand).Register::scope();
1048
#if LLINT_SLOW_PATH_TRACING
1049
    dataLogF("Creating async function!\n");
1050
#endif
1051
    LLINT_RETURN(JSAsyncFunction::create(vm, codeBlock->functionDecl(pc[3].u.operand), scope));
1052
}
1053
1042
LLINT_SLOW_PATH_DECL(slow_path_new_generator_func)
1054
LLINT_SLOW_PATH_DECL(slow_path_new_generator_func)
1043
{
1055
{
1044
    LLINT_BEGIN();
1056
    LLINT_BEGIN();
Lines 1072-1077 LLINT_SLOW_PATH_DECL(slow_path_new_generator_func_exp) a/Source/JavaScriptCore/llint/LLIntSlowPaths.cpp_sec3
1072
    LLINT_RETURN(JSGeneratorFunction::create(vm, executable, scope));
1084
    LLINT_RETURN(JSGeneratorFunction::create(vm, executable, scope));
1073
}
1085
}
1074
1086
1087
LLINT_SLOW_PATH_DECL(slow_path_new_async_func_exp)
1088
{
1089
    LLINT_BEGIN();
1090
    
1091
    CodeBlock* codeBlock = exec->codeBlock();
1092
    JSScope* scope = exec->uncheckedR(pc[2].u.operand).Register::scope();
1093
    FunctionExecutable* executable = codeBlock->functionExpr(pc[3].u.operand);
1094
    
1095
    LLINT_RETURN(JSAsyncFunction::create(vm, executable, scope));
1096
}
1097
1075
LLINT_SLOW_PATH_DECL(slow_path_new_arrow_func_exp)
1098
LLINT_SLOW_PATH_DECL(slow_path_new_arrow_func_exp)
1076
{
1099
{
1077
    LLINT_BEGIN();
1100
    LLINT_BEGIN();
- a/Source/JavaScriptCore/llint/LLIntSlowPaths.h +2 lines
Lines 99-104 LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_switch_char); a/Source/JavaScriptCore/llint/LLIntSlowPaths.h_sec1
99
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_switch_string);
99
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_switch_string);
100
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_func);
100
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_func);
101
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_func_exp);
101
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_func_exp);
102
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_async_func);
103
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_async_func_exp);
102
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_generator_func);
104
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_generator_func);
103
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_generator_func_exp);
105
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_generator_func_exp);
104
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_arrow_func_exp);
106
LLINT_SLOW_PATH_HIDDEN_DECL(slow_path_new_arrow_func_exp);
- a/Source/JavaScriptCore/llint/LowLevelInterpreter.asm -1 / +11 lines
Lines 1218-1223 _llint_op_new_func: a/Source/JavaScriptCore/llint/LowLevelInterpreter.asm_sec1
1218
    dispatch(4)
1218
    dispatch(4)
1219
1219
1220
1220
1221
_llint_op_new_async_func:
1222
    traceExecution()
1223
    callSlowPath(_llint_slow_path_new_async_func)
1224
    dispatch(4)
1225
1226
1221
_llint_op_new_generator_func:
1227
_llint_op_new_generator_func:
1222
    traceExecution()
1228
    traceExecution()
1223
    callSlowPath(_llint_slow_path_new_generator_func)
1229
    callSlowPath(_llint_slow_path_new_generator_func)
Lines 1455-1461 _llint_op_switch_string: a/Source/JavaScriptCore/llint/LowLevelInterpreter.asm_sec2
1455
    callSlowPath(_llint_slow_path_switch_string)
1461
    callSlowPath(_llint_slow_path_switch_string)
1456
    dispatch(0)
1462
    dispatch(0)
1457
1463
1458
1459
_llint_op_new_func_exp:
1464
_llint_op_new_func_exp:
1460
    traceExecution()
1465
    traceExecution()
1461
    callSlowPath(_llint_slow_path_new_func_exp)
1466
    callSlowPath(_llint_slow_path_new_func_exp)
Lines 1466-1471 _llint_op_new_generator_func_exp: a/Source/JavaScriptCore/llint/LowLevelInterpreter.asm_sec3
1466
    callSlowPath(_llint_slow_path_new_generator_func_exp)
1471
    callSlowPath(_llint_slow_path_new_generator_func_exp)
1467
    dispatch(4)
1472
    dispatch(4)
1468
1473
1474
_llint_op_new_async_func_exp:
1475
    traceExecution()
1476
    callSlowPath(_llint_slow_path_new_async_func_exp)
1477
    dispatch(4)
1478
1469
_llint_op_new_arrow_func_exp:
1479
_llint_op_new_arrow_func_exp:
1470
    traceExecution()
1480
    traceExecution()
1471
    callSlowPath(_llint_slow_path_new_arrow_func_exp)
1481
    callSlowPath(_llint_slow_path_new_arrow_func_exp)
- a/Source/JavaScriptCore/parser/Keywords.table +2 lines
Lines 7-12 true TRUETOKEN a/Source/JavaScriptCore/parser/Keywords.table_sec1
7
false		FALSETOKEN
7
false		FALSETOKEN
8
8
9
# Keywords.
9
# Keywords.
10
async		ASYNC
11
await		AWAIT
10
break		BREAK
12
break		BREAK
11
case		CASE
13
case		CASE
12
catch		CATCH
14
catch		CATCH
- a/Source/JavaScriptCore/parser/Parser.cpp -43 / +301 lines
Lines 74-80 a/Source/JavaScriptCore/parser/Parser.cpp_sec1
74
        semanticFail("Cannot use the reserved word '", getToken(), "' as a ", __VA_ARGS__, " in strict mode"); \
74
        semanticFail("Cannot use the reserved word '", getToken(), "' as a ", __VA_ARGS__, " in strict mode"); \
75
    if (m_token.m_type == RESERVED || m_token.m_type == RESERVED_IF_STRICT) \
75
    if (m_token.m_type == RESERVED || m_token.m_type == RESERVED_IF_STRICT) \
76
        semanticFail("Cannot use the reserved word '", getToken(), "' as a ", __VA_ARGS__); \
76
        semanticFail("Cannot use the reserved word '", getToken(), "' as a ", __VA_ARGS__); \
77
    if (m_token.m_type & KeywordTokenFlag) \
77
    if (isDisallowedIdentifierAwait(m_token)) \
78
        semanticFail("Can't use 'await' as a ", __VA_ARGS__, " ", disallowedIdentifierAwaitReason()); \
79
    else if (m_token.m_type & KeywordTokenFlag) \
78
        semanticFail("Cannot use the keyword '", getToken(), "' as a ", __VA_ARGS__); \
80
        semanticFail("Cannot use the keyword '", getToken(), "' as a ", __VA_ARGS__); \
79
} while (0)
81
} while (0)
80
82
Lines 230-235 Parser<LexerType>::Parser(VM* vm, const SourceCode& source, JSParserBuiltinMode a/Source/JavaScriptCore/parser/Parser.cpp_sec2
230
    if (strictMode == JSParserStrictMode::Strict)
232
    if (strictMode == JSParserStrictMode::Strict)
231
        scope->setStrictMode();
233
        scope->setStrictMode();
232
234
235
    m_allowsAwait = true;
236
233
    next();
237
    next();
234
}
238
}
235
239
Lines 248-263 String Parser<LexerType>::parseInner(const Identifier& calleeName, SourceParseMo a/Source/JavaScriptCore/parser/Parser.cpp_sec3
248
    scope->setIsLexicalScope();
252
    scope->setIsLexicalScope();
249
    SetForScope<FunctionParsePhase> functionParsePhasePoisoner(m_parserState.functionParsePhase, FunctionParsePhase::Body);
253
    SetForScope<FunctionParsePhase> functionParsePhasePoisoner(m_parserState.functionParsePhase, FunctionParsePhase::Body);
250
254
251
    bool isArrowFunctionBodyExpression = false;
255
    bool isArrowFunctionBodyExpression = parseMode == SourceParseMode::AsyncArrowFunctionBodyMode && !match(OPENBRACE);
252
    if (m_lexer->isReparsingFunction()) {
256
    if (m_lexer->isReparsingFunction()) {
253
        ParserFunctionInfo<ASTBuilder> functionInfo;
257
        ParserFunctionInfo<ASTBuilder> functionInfo;
254
        if (parseMode == SourceParseMode::GeneratorBodyMode)
258
        if (parseMode == SourceParseMode::GeneratorBodyMode || isAsyncFunctionBodyParseMode(parseMode))
255
            functionInfo.parameters = createGeneratorParameters(context);
259
            functionInfo.parameters = createGeneratorParameters(context);
256
        else
260
        else
257
            parseFunctionParameters(context, parseMode, functionInfo);
261
            parseFunctionParameters(context, parseMode, functionInfo);
258
        m_parameters = functionInfo.parameters;
262
        m_parameters = functionInfo.parameters;
259
263
260
        if (parseMode == SourceParseMode::ArrowFunctionMode && !hasError()) {
264
        if ((parseMode == SourceParseMode::ArrowFunctionMode || parseMode == SourceParseMode::AsyncArrowFunctionMode) && !hasError()) {
261
            // The only way we could have an error wile reparsing is if we run out of stack space.
265
            // The only way we could have an error wile reparsing is if we run out of stack space.
262
            RELEASE_ASSERT(match(ARROWFUNCTION));
266
            RELEASE_ASSERT(match(ARROWFUNCTION));
263
            next();
267
            next();
Lines 274-289 String Parser<LexerType>::parseInner(const Identifier& calleeName, SourceParseMo a/Source/JavaScriptCore/parser/Parser.cpp_sec4
274
    SourceElements* sourceElements = nullptr;
278
    SourceElements* sourceElements = nullptr;
275
    // The only way we can error this early is if we reparse a function and we run out of stack space.
279
    // The only way we can error this early is if we reparse a function and we run out of stack space.
276
    if (!hasError()) {
280
    if (!hasError()) {
277
        if (isArrowFunctionBodyExpression)
281
        if (isAsyncFunctionWrapperParseMode(parseMode))
282
            sourceElements = parseAsyncFunctionSourceElements(context, parseMode, isArrowFunctionBodyExpression, CheckForStrictMode);
283
        else if (isArrowFunctionBodyExpression)
278
            sourceElements = parseArrowFunctionSingleExpressionBodySourceElements(context);
284
            sourceElements = parseArrowFunctionSingleExpressionBodySourceElements(context);
279
        else if (isModuleParseMode(parseMode))
285
        else if (isModuleParseMode(parseMode))
280
            sourceElements = parseModuleSourceElements(context, parseMode);
286
            sourceElements = parseModuleSourceElements(context, parseMode);
281
        else {
287
        else if (parseMode == SourceParseMode::GeneratorWrapperFunctionMode)
282
            if (parseMode == SourceParseMode::GeneratorWrapperFunctionMode)
288
            sourceElements = parseGeneratorFunctionSourceElements(context, CheckForStrictMode);
283
                sourceElements = parseGeneratorFunctionSourceElements(context, CheckForStrictMode);
289
        else
284
            else
290
            sourceElements = parseSourceElements(context, CheckForStrictMode);
285
                sourceElements = parseSourceElements(context, CheckForStrictMode);
286
        }
287
    }
291
    }
288
292
289
    bool validEnding;
293
    bool validEnding;
Lines 312-318 String Parser<LexerType>::parseInner(const Identifier& calleeName, SourceParseMo a/Source/JavaScriptCore/parser/Parser.cpp_sec5
312
    for (auto& entry : capturedVariables)
316
    for (auto& entry : capturedVariables)
313
        varDeclarations.markVariableAsCaptured(entry);
317
        varDeclarations.markVariableAsCaptured(entry);
314
318
315
    if (parseMode == SourceParseMode::GeneratorWrapperFunctionMode) {
319
    if (parseMode == SourceParseMode::GeneratorWrapperFunctionMode || isAsyncFunctionWrapperParseMode(parseMode)) {
316
        if (scope->usedVariablesContains(m_vm->propertyNames->arguments.impl()))
320
        if (scope->usedVariablesContains(m_vm->propertyNames->arguments.impl()))
317
            context.propagateArgumentsUse();
321
            context.propagateArgumentsUse();
318
    }
322
    }
Lines 361-367 template <typename LexerType> a/Source/JavaScriptCore/parser/Parser.cpp_sec6
361
bool Parser<LexerType>::isArrowFunctionParameters()
365
bool Parser<LexerType>::isArrowFunctionParameters()
362
{
366
{
363
    bool isOpenParen = match(OPENPAREN);
367
    bool isOpenParen = match(OPENPAREN);
364
    bool isIdent = match(IDENT);
368
    bool isIdent = matchSpecIdentifier();
365
    
369
    
366
    if (!isOpenParen && !isIdent)
370
    if (!isOpenParen && !isIdent)
367
        return false;
371
        return false;
Lines 534-539 template <class TreeBuilder> TreeSourceElements Parser<LexerType>::parseGenerato a/Source/JavaScriptCore/parser/Parser.cpp_sec7
534
}
538
}
535
539
536
template <typename LexerType>
540
template <typename LexerType>
541
template <class TreeBuilder> TreeSourceElements Parser<LexerType>::parseAsyncFunctionSourceElements(TreeBuilder& context, SourceParseMode parseMode, bool isArrowFunctionBodyExpression, SourceElementsMode mode)
542
{
543
    ASSERT(isAsyncFunctionWrapperParseMode(parseMode));
544
    auto sourceElements = context.createSourceElements();
545
546
    unsigned functionKeywordStart = tokenStart();
547
    JSTokenLocation startLocation(tokenLocation());
548
    JSTextPosition start = tokenStartPosition();
549
    unsigned startColumn = tokenColumn();
550
    int functionNameStart = m_token.m_location.startOffset;
551
    int parametersStart = m_token.m_location.startOffset;
552
553
    ParserFunctionInfo<TreeBuilder> info;
554
    info.name = &m_vm->propertyNames->nullIdentifier;
555
    info.parameters = createGeneratorParameters(context);
556
    info.startOffset = parametersStart;
557
    info.startLine = tokenLine();
558
    info.parameterCount = 4; // generator, state, value, resume mode
559
    SourceParseMode innerParseMode = parseMode == SourceParseMode::AsyncArrowFunctionMode ? SourceParseMode::AsyncArrowFunctionBodyMode : SourceParseMode::AsyncFunctionBodyMode;
560
    {
561
        AutoPopScopeRef asyncFunctionBodyScope(this, pushScope());
562
        asyncFunctionBodyScope->setSourceParseMode(innerParseMode);
563
        SyntaxChecker asyncFunctionContext(const_cast<VM*>(m_vm), m_lexer.get());
564
        if (isArrowFunctionBodyExpression)
565
            failIfFalse(parseArrowFunctionSingleExpressionBodySourceElements(asyncFunctionContext), "Cannot parse the body of async arrow function");
566
        else
567
            failIfFalse(parseSourceElements(asyncFunctionContext, mode), "Cannot parse the body of async function");
568
        popScope(asyncFunctionBodyScope, TreeBuilder::NeedsFreeVariableInfo);
569
    }
570
571
    info.body = context.createFunctionMetadata(startLocation, tokenLocation(), startColumn, tokenColumn(), functionKeywordStart, functionNameStart, parametersStart, strictMode(), ConstructorKind::None, m_superBinding, info.parameterCount, innerParseMode, isArrowFunctionBodyExpression);
572
573
    info.endLine = tokenLine();
574
    info.endOffset = m_token.m_data.offset;
575
    info.bodyStartColumn = startColumn;
576
577
    auto functionExpr = context.createFunctionExpr(startLocation, info);
578
    auto statement = context.createExprStatement(startLocation, functionExpr, start, m_lastTokenEndPosition.line);
579
    context.appendStatement(sourceElements, statement);
580
581
    return sourceElements;
582
}
583
584
template <typename LexerType>
537
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseStatementListItem(TreeBuilder& context, const Identifier*& directive, unsigned* directiveLiteralLength)
585
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseStatementListItem(TreeBuilder& context, const Identifier*& directive, unsigned* directiveLiteralLength)
538
{
586
{
539
    // The grammar is documented here:
587
    // The grammar is documented here:
Lines 542-547 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseStatementList a/Source/JavaScriptCore/parser/Parser.cpp_sec8
542
    m_statementDepth++;
590
    m_statementDepth++;
543
    TreeStatement result = 0;
591
    TreeStatement result = 0;
544
    bool shouldSetEndOffset = true;
592
    bool shouldSetEndOffset = true;
593
594
    if (UNLIKELY(match(ASYNC))) {
595
        SavePoint beforeAsync = createSavePoint();
596
        next();
597
        if (match(FUNCTION) && !m_lexer->prevTerminator()) {
598
            result = parseAsyncFunctionDeclaration(context);
599
            failIfFalse(result, "Failed to parse async function declaration");
600
            context.setEndOffset(result, m_lastTokenEndPosition.offset);
601
            return result;
602
        }
603
        restoreSavePoint(beforeAsync);
604
    }
605
545
    switch (m_token.m_type) {
606
    switch (m_token.m_type) {
546
    case CONSTTOKEN:
607
    case CONSTTOKEN:
547
        result = parseVariableDeclaration(context, DeclarationType::ConstDeclaration);
608
        result = parseVariableDeclaration(context, DeclarationType::ConstDeclaration);
Lines 556-562 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseStatementList a/Source/JavaScriptCore/parser/Parser.cpp_sec9
556
            // For example, under a generator context, matchSpecIdentifier() for "yield" returns `false`.
617
            // For example, under a generator context, matchSpecIdentifier() for "yield" returns `false`.
557
            // But we would like to enter parseVariableDeclaration and raise an error under the context of parseVariableDeclaration
618
            // But we would like to enter parseVariableDeclaration and raise an error under the context of parseVariableDeclaration
558
            // to raise consistent errors between "var", "const" and "let".
619
            // to raise consistent errors between "var", "const" and "let".
559
            if (!(match(IDENT) || match(LET) || match(YIELD)) && !match(OPENBRACE) && !match(OPENBRACKET))
620
            if (!(match(IDENT) || match(ASYNC) || match(AWAIT) || match(LET) || match(YIELD)) && !match(OPENBRACE) && !match(OPENBRACKET))
560
                shouldParseVariableDeclaration = false;
621
                shouldParseVariableDeclaration = false;
561
            restoreSavePoint(savePoint);
622
            restoreSavePoint(savePoint);
562
        }
623
        }
Lines 575-580 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseStatementList a/Source/JavaScriptCore/parser/Parser.cpp_sec10
575
    case FUNCTION:
636
    case FUNCTION:
576
        result = parseFunctionDeclaration(context);
637
        result = parseFunctionDeclaration(context);
577
        break;
638
        break;
639
578
    default:
640
    default:
579
        m_statementDepth--; // parseStatement() increments the depth.
641
        m_statementDepth--; // parseStatement() increments the depth.
580
        result = parseStatement(context, directive, directiveLiteralLength);
642
        result = parseStatement(context, directive, directiveLiteralLength);
Lines 674-679 template <class TreeBuilder> TreeExpression Parser<LexerType>::parseVariableDecl a/Source/JavaScriptCore/parser/Parser.cpp_sec11
674
        if (matchSpecIdentifier()) {
736
        if (matchSpecIdentifier()) {
675
            failIfTrue(match(LET) && (declarationType == DeclarationType::LetDeclaration || declarationType == DeclarationType::ConstDeclaration), 
737
            failIfTrue(match(LET) && (declarationType == DeclarationType::LetDeclaration || declarationType == DeclarationType::ConstDeclaration), 
676
                "Can't use 'let' as an identifier name for a LexicalDeclaration");
738
                "Can't use 'let' as an identifier name for a LexicalDeclaration");
739
            semanticFailIfTrue(isDisallowedIdentifierAwait(m_token), "Can't use 'await' as a ", declarationTypeToVariableKind(declarationType), " ", disallowedIdentifierAwaitReason());
677
            JSTextPosition varStart = tokenStartPosition();
740
            JSTextPosition varStart = tokenStartPosition();
678
            JSTokenLocation varStartLocation(tokenLocation());
741
            JSTokenLocation varStartLocation(tokenLocation());
679
            identStart = varStart;
742
            identStart = varStart;
Lines 1000-1005 template <class TreeBuilder> TreeDestructuringPattern Parser<LexerType>::parseDe a/Source/JavaScriptCore/parser/Parser.cpp_sec12
1000
                            reclassifyExpressionError(ErrorIndicatesPattern, ErrorIndicatesNothing);
1063
                            reclassifyExpressionError(ErrorIndicatesPattern, ErrorIndicatesNothing);
1001
                        failIfTrueIfStrict(isEvalOrArguments, "Cannot modify '", propertyName->impl(), "' in strict mode");
1064
                        failIfTrueIfStrict(isEvalOrArguments, "Cannot modify '", propertyName->impl(), "' in strict mode");
1002
                    }
1065
                    }
1066
                    semanticFailIfTrue(isDisallowedIdentifierAwait(identifierToken), "Can't use 'await' as a ", destructuringKindToVariableKindName(kind), " ", disallowedIdentifierAwaitReason());
1003
                    innerPattern = createBindingPattern(context, kind, exportType, *propertyName, identifierToken, bindingContext, duplicateIdentifier);
1067
                    innerPattern = createBindingPattern(context, kind, exportType, *propertyName, identifierToken, bindingContext, duplicateIdentifier);
1004
                }
1068
                }
1005
            } else {
1069
            } else {
Lines 1067-1072 template <class TreeBuilder> TreeDestructuringPattern Parser<LexerType>::parseDe a/Source/JavaScriptCore/parser/Parser.cpp_sec13
1067
            failWithMessage("Expected a parameter pattern or a ')' in parameter list");
1131
            failWithMessage("Expected a parameter pattern or a ')' in parameter list");
1068
        }
1132
        }
1069
        failIfTrue(match(LET) && (kind == DestructuringKind::DestructureToLet || kind == DestructuringKind::DestructureToConst), "Can't use 'let' as an identifier name for a LexicalDeclaration");
1133
        failIfTrue(match(LET) && (kind == DestructuringKind::DestructureToLet || kind == DestructuringKind::DestructureToConst), "Can't use 'let' as an identifier name for a LexicalDeclaration");
1134
        semanticFailIfTrue(isDisallowedIdentifierAwait(m_token), "Can't use 'await' as a ", destructuringKindToVariableKindName(kind), " ", disallowedIdentifierAwaitReason());
1070
        pattern = createBindingPattern(context, kind, exportType, *m_token.m_data.ident, m_token, bindingContext, duplicateIdentifier);
1135
        pattern = createBindingPattern(context, kind, exportType, *m_token.m_data.ident, m_token, bindingContext, duplicateIdentifier);
1071
        next();
1136
        next();
1072
        break;
1137
        break;
Lines 1667-1672 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseStatement(Tre a/Source/JavaScriptCore/parser/Parser.cpp_sec14
1667
        // These tokens imply the end of a set of source elements
1732
        // These tokens imply the end of a set of source elements
1668
        return 0;
1733
        return 0;
1669
    case IDENT:
1734
    case IDENT:
1735
    case ASYNC:
1736
    case AWAIT:
1670
    case YIELD:
1737
    case YIELD:
1671
        result = parseExpressionOrLabelStatement(context);
1738
        result = parseExpressionOrLabelStatement(context);
1672
        break;
1739
        break;
Lines 1709-1714 template <class TreeBuilder> bool Parser<LexerType>::parseFormalParameters(TreeB a/Source/JavaScriptCore/parser/Parser.cpp_sec15
1709
        if (match(DOTDOTDOT)) {
1776
        if (match(DOTDOTDOT)) {
1710
            next();
1777
            next();
1711
            failIfFalse(matchSpecIdentifier(), "Rest parameter '...' should be followed by a variable identifier");
1778
            failIfFalse(matchSpecIdentifier(), "Rest parameter '...' should be followed by a variable identifier");
1779
            semanticFailIfTrue(!m_allowsAwait && match(AWAIT), "Can't use 'await' as a parameter name in an async function");
1712
            declareRestOrNormalParameter(*m_token.m_data.ident, &duplicateParameter);
1780
            declareRestOrNormalParameter(*m_token.m_data.ident, &duplicateParameter);
1713
            propagateError();
1781
            propagateError();
1714
            JSTextPosition identifierStart = tokenStartPosition();
1782
            JSTextPosition identifierStart = tokenStartPosition();
Lines 1775-1780 static const char* stringForFunctionMode(SourceParseMode mode) a/Source/JavaScriptCore/parser/Parser.cpp_sec16
1775
        return "generator function";
1843
        return "generator function";
1776
    case SourceParseMode::ArrowFunctionMode:
1844
    case SourceParseMode::ArrowFunctionMode:
1777
        return "arrow function";
1845
        return "arrow function";
1846
    case SourceParseMode::AsyncFunctionMode:
1847
    case SourceParseMode::AsyncFunctionBodyMode:
1848
        return "async function";
1849
    case SourceParseMode::AsyncMethodMode:
1850
        return "async method";
1851
    case SourceParseMode::AsyncArrowFunctionBodyMode:
1852
    case SourceParseMode::AsyncArrowFunctionMode:
1853
        return "async arrow function";
1778
    case SourceParseMode::ProgramMode:
1854
    case SourceParseMode::ProgramMode:
1779
    case SourceParseMode::ModuleAnalyzeMode:
1855
    case SourceParseMode::ModuleAnalyzeMode:
1780
    case SourceParseMode::ModuleEvaluateMode:
1856
    case SourceParseMode::ModuleEvaluateMode:
Lines 1794-1801 template <typename LexerType> template <class TreeBuilder> int Parser<LexerType> a/Source/JavaScriptCore/parser/Parser.cpp_sec17
1794
    functionInfo.startOffset = parametersStart;
1870
    functionInfo.startOffset = parametersStart;
1795
    SetForScope<FunctionParsePhase> functionParsePhasePoisoner(m_parserState.functionParsePhase, FunctionParsePhase::Parameters);
1871
    SetForScope<FunctionParsePhase> functionParsePhasePoisoner(m_parserState.functionParsePhase, FunctionParsePhase::Parameters);
1796
    
1872
    
1797
    if (mode == SourceParseMode::ArrowFunctionMode) {
1873
    if (mode == SourceParseMode::ArrowFunctionMode || mode == SourceParseMode::AsyncArrowFunctionMode) {
1798
        if (!match(IDENT) && !match(OPENPAREN)) {
1874
        if (!matchSpecIdentifier() && !match(OPENPAREN)) {
1799
            semanticFailureDueToKeyword(stringForFunctionMode(mode), " name");
1875
            semanticFailureDueToKeyword(stringForFunctionMode(mode), " name");
1800
            failWithMessage("Expected an arrow function input parameter");
1876
            failWithMessage("Expected an arrow function input parameter");
1801
        } else {
1877
        } else {
Lines 1887-1892 template <class TreeBuilder> bool Parser<LexerType>::parseFunctionInfo(TreeBuild a/Source/JavaScriptCore/parser/Parser.cpp_sec18
1887
    RELEASE_ASSERT(isFunctionParseMode(mode));
1963
    RELEASE_ASSERT(isFunctionParseMode(mode));
1888
1964
1889
    bool upperScopeIsGenerator = currentScope()->isGenerator();
1965
    bool upperScopeIsGenerator = currentScope()->isGenerator();
1966
    bool upperScopeIsAsync = currentScope()->isAsyncFunctionBoundary();
1967
    bool isDisallowedAwaitFunctionName = isDisallowedIdentifierAwait(m_token);
1968
    const char* isDisallowedAwaitFunctionNameReason = isDisallowedAwaitFunctionName ? disallowedIdentifierAwaitReason() : nullptr;
1890
    AutoPopScopeRef functionScope(this, pushScope());
1969
    AutoPopScopeRef functionScope(this, pushScope());
1891
    functionScope->setSourceParseMode(mode);
1970
    functionScope->setSourceParseMode(mode);
1892
    SetForScope<FunctionParsePhase> functionParsePhasePoisoner(m_parserState.functionParsePhase, FunctionParsePhase::Body);
1971
    SetForScope<FunctionParsePhase> functionParsePhasePoisoner(m_parserState.functionParsePhase, FunctionParsePhase::Body);
Lines 1898-1909 template <class TreeBuilder> bool Parser<LexerType>::parseFunctionInfo(TreeBuild a/Source/JavaScriptCore/parser/Parser.cpp_sec19
1898
    int startColumn;
1977
    int startColumn;
1899
    FunctionBodyType functionBodyType;
1978
    FunctionBodyType functionBodyType;
1900
1979
1901
    if (mode == SourceParseMode::ArrowFunctionMode) {
1980
    if (mode == SourceParseMode::ArrowFunctionMode || mode == SourceParseMode::AsyncArrowFunctionMode) {
1902
        startLocation = tokenLocation();
1981
        startLocation = tokenLocation();
1903
        functionInfo.startLine = tokenLine();
1982
        functionInfo.startLine = tokenLine();
1904
        startColumn = tokenColumn();
1983
        startColumn = tokenColumn();
1905
1984
1906
        parametersStart = parseFunctionParameters(context, mode, functionInfo);
1985
        {
1986
            AllowAwaitOverride allowAwait(this, !isAsyncFunctionParseMode(mode));
1987
            parametersStart = parseFunctionParameters(context, mode, functionInfo);
1988
        }
1907
        propagateError();
1989
        propagateError();
1908
1990
1909
        matchOrFail(ARROWFUNCTION, "Expected a '=>' after arrow function parameter declaration");
1991
        matchOrFail(ARROWFUNCTION, "Expected a '=>' after arrow function parameter declaration");
Lines 1933-1951 template <class TreeBuilder> bool Parser<LexerType>::parseFunctionInfo(TreeBuild a/Source/JavaScriptCore/parser/Parser.cpp_sec20
1933
        // GeneratorExpression :
2015
        // GeneratorExpression :
1934
        //     function * BindingIdentifier[Yield]opt ( FormalParameters[Yield] ) { GeneratorBody }
2016
        //     function * BindingIdentifier[Yield]opt ( FormalParameters[Yield] ) { GeneratorBody }
1935
        //
2017
        //
1936
        // The name of FunctionExpression can accept "yield" even in the context of generator.
2018
        // The name of FunctionExpression and AsyncFunctionExpression can accept "yield" even in the context of generator.
1937
        if (functionDefinitionType == FunctionDefinitionType::Expression && mode == SourceParseMode::NormalFunctionMode)
2019
        if (functionDefinitionType == FunctionDefinitionType::Expression && (mode == SourceParseMode::NormalFunctionMode || mode == SourceParseMode::AsyncFunctionMode))
1938
            upperScopeIsGenerator = false;
2020
            upperScopeIsGenerator = false;
1939
2021
1940
        if (matchSpecIdentifier(upperScopeIsGenerator)) {
2022
        if (matchSpecIdentifier(upperScopeIsGenerator)) {
2023
            bool allowsAwait = mode != SourceParseMode::AsyncFunctionMode;
2024
            if (functionDefinitionType == FunctionDefinitionType::Declaration)
2025
                allowsAwait = upperScopeIsAsync;
1941
            functionInfo.name = m_token.m_data.ident;
2026
            functionInfo.name = m_token.m_data.ident;
1942
            m_parserState.lastFunctionName = functionInfo.name;
2027
            m_parserState.lastFunctionName = functionInfo.name;
2028
            if (allowsAwait)
2029
                semanticFailIfTrue(isDisallowedAwaitFunctionName, "Cannot declare function named 'await' ", isDisallowedAwaitFunctionNameReason);
2030
            else
2031
                semanticFailIfTrue(isDisallowedAwaitFunctionName, "Cannot declare async function named 'await'");
2032
            
1943
            next();
2033
            next();
1944
            if (!nameIsInContainingScope)
2034
            if (!nameIsInContainingScope)
1945
                failIfTrueIfStrict(functionScope->declareCallee(functionInfo.name) & DeclarationResult::InvalidStrictMode, "'", functionInfo.name->impl(), "' is not a valid ", stringForFunctionMode(mode), " name in strict mode");
2035
                failIfTrueIfStrict(functionScope->declareCallee(functionInfo.name) & DeclarationResult::InvalidStrictMode, "'", functionInfo.name->impl(), "' is not a valid ", stringForFunctionMode(mode), " name in strict mode");
1946
        } else if (requirements == FunctionNeedsName) {
2036
        } else if (requirements == FunctionNeedsName) {
1947
            if (match(OPENPAREN) && mode == SourceParseMode::NormalFunctionMode)
2037
            semanticFailIfTrue(match(OPENPAREN) && mode == SourceParseMode::NormalFunctionMode, "Function statements must have a name");
1948
                semanticFail("Function statements must have a name");
2038
            semanticFailIfTrue(match(OPENPAREN) && mode == SourceParseMode::AsyncFunctionMode, "Async function statements must have a name");
1949
            semanticFailureDueToKeyword(stringForFunctionMode(mode), " name");
2039
            semanticFailureDueToKeyword(stringForFunctionMode(mode), " name");
1950
            failDueToUnexpectedToken();
2040
            failDueToUnexpectedToken();
1951
            return false;
2041
            return false;
Lines 1955-1961 template <class TreeBuilder> bool Parser<LexerType>::parseFunctionInfo(TreeBuild a/Source/JavaScriptCore/parser/Parser.cpp_sec21
1955
        functionInfo.startLine = tokenLine();
2045
        functionInfo.startLine = tokenLine();
1956
        startColumn = tokenColumn();
2046
        startColumn = tokenColumn();
1957
2047
1958
        parametersStart = parseFunctionParameters(context, mode, functionInfo);
2048
        {
2049
            AllowAwaitOverride allowAwait(this, !isAsyncFunctionParseMode(mode));
2050
            parametersStart = parseFunctionParameters(context, mode, functionInfo);
2051
        }
1959
        propagateError();
2052
        propagateError();
1960
        
2053
        
1961
        matchOrFail(OPENBRACE, "Expected an opening '{' at the start of a ", stringForFunctionMode(mode), " body");
2054
        matchOrFail(OPENBRACE, "Expected an opening '{' at the start of a ", stringForFunctionMode(mode), " body");
Lines 2010-2016 template <class TreeBuilder> bool Parser<LexerType>::parseFunctionInfo(TreeBuild a/Source/JavaScriptCore/parser/Parser.cpp_sec22
2010
        m_lexer->setLineNumber(m_token.m_location.line);
2103
        m_lexer->setLineNumber(m_token.m_location.line);
2011
        functionInfo.endOffset = cachedInfo->endFunctionOffset;
2104
        functionInfo.endOffset = cachedInfo->endFunctionOffset;
2012
2105
2013
        if (mode == SourceParseMode::ArrowFunctionMode)
2106
        if (mode == SourceParseMode::ArrowFunctionMode || mode == SourceParseMode::AsyncArrowFunctionMode)
2014
            functionBodyType = cachedInfo->isBodyArrowExpression ?  ArrowFunctionBodyExpression : ArrowFunctionBodyBlock;
2107
            functionBodyType = cachedInfo->isBodyArrowExpression ?  ArrowFunctionBodyExpression : ArrowFunctionBodyBlock;
2015
        else
2108
        else
2016
            functionBodyType = StandardFunctionBodyBlock;
2109
            functionBodyType = StandardFunctionBodyBlock;
Lines 2037-2054 template <class TreeBuilder> bool Parser<LexerType>::parseFunctionInfo(TreeBuild a/Source/JavaScriptCore/parser/Parser.cpp_sec23
2037
        return parseFunctionBody(context, startLocation, startColumn, functionKeywordStart, functionNameStart, parametersStart, constructorKind, expectedSuperBinding, functionBodyType, functionInfo.parameterCount, mode);
2130
        return parseFunctionBody(context, startLocation, startColumn, functionKeywordStart, functionNameStart, parametersStart, constructorKind, expectedSuperBinding, functionBodyType, functionInfo.parameterCount, mode);
2038
    };
2131
    };
2039
2132
2040
    if (mode == SourceParseMode::GeneratorWrapperFunctionMode) {
2133
    if (mode == SourceParseMode::GeneratorWrapperFunctionMode || isAsyncFunctionWrapperParseMode(mode)) {
2041
        AutoPopScopeRef generatorBodyScope(this, pushScope());
2134
        AutoPopScopeRef generatorBodyScope(this, pushScope());
2042
        generatorBodyScope->setSourceParseMode(SourceParseMode::GeneratorBodyMode);
2135
        SourceParseMode innerParseMode = SourceParseMode::GeneratorBodyMode;
2136
        if (isAsyncFunctionWrapperParseMode(mode)) {
2137
            innerParseMode = mode == SourceParseMode::AsyncArrowFunctionMode
2138
                ? SourceParseMode::AsyncArrowFunctionBodyMode
2139
                : SourceParseMode::AsyncFunctionBodyMode;
2140
        }
2141
        generatorBodyScope->setSourceParseMode(innerParseMode);
2043
        functionInfo.body = performParsingFunctionBody();
2142
        functionInfo.body = performParsingFunctionBody();
2044
2143
2045
        // When a generator has a "use strict" directive, a generator function wrapping it should be strict mode.
2144
        // When a generator has a "use strict" directive, a generator function wrapping it should be strict mode.
2046
        if  (generatorBodyScope->strictMode())
2145
        if  (generatorBodyScope->strictMode())
2047
            functionScope->setStrictMode();
2146
            functionScope->setStrictMode();
2048
2147
2049
        semanticFailIfTrue(generatorBodyScope->hasDirectSuper(), "Cannot call super() outside of a class constructor");
2148
        if (mode != SourceParseMode::AsyncArrowFunctionMode) {
2050
        if (generatorBodyScope->needsSuperBinding())
2149
            semanticFailIfTrue(generatorBodyScope->hasDirectSuper(), "Cannot call super() outside of a class constructor");
2051
            semanticFailIfTrue(expectedSuperBinding == SuperBinding::NotNeeded, "super can only be used in a method of a derived class");
2150
            if (generatorBodyScope->needsSuperBinding())
2151
                semanticFailIfTrue(expectedSuperBinding == SuperBinding::NotNeeded, "super can only be used in a method of a derived class");
2152
        } else {
2153
            if (generatorBodyScope->hasDirectSuper())
2154
                functionScope->setHasDirectSuper();
2155
            if (generatorBodyScope->needsSuperBinding())
2156
                functionScope->setNeedsSuperBinding();
2157
        }
2052
2158
2053
        popScope(generatorBodyScope, TreeBuilder::NeedsFreeVariableInfo);
2159
        popScope(generatorBodyScope, TreeBuilder::NeedsFreeVariableInfo);
2054
    } else
2160
    } else
Lines 2058-2064 template <class TreeBuilder> bool Parser<LexerType>::parseFunctionInfo(TreeBuild a/Source/JavaScriptCore/parser/Parser.cpp_sec24
2058
    failIfFalse(functionInfo.body, "Cannot parse the body of this ", stringForFunctionMode(mode));
2164
    failIfFalse(functionInfo.body, "Cannot parse the body of this ", stringForFunctionMode(mode));
2059
    context.setEndOffset(functionInfo.body, m_lexer->currentOffset());
2165
    context.setEndOffset(functionInfo.body, m_lexer->currentOffset());
2060
    if (functionScope->strictMode() && functionInfo.name) {
2166
    if (functionScope->strictMode() && functionInfo.name) {
2061
        RELEASE_ASSERT(mode == SourceParseMode::NormalFunctionMode || mode == SourceParseMode::MethodMode || mode == SourceParseMode::ArrowFunctionMode || mode == SourceParseMode::GeneratorBodyMode || mode == SourceParseMode::GeneratorWrapperFunctionMode);
2167
        RELEASE_ASSERT(mode == SourceParseMode::NormalFunctionMode || mode == SourceParseMode::MethodMode || mode == SourceParseMode::ArrowFunctionMode || mode == SourceParseMode::GeneratorBodyMode || mode == SourceParseMode::GeneratorWrapperFunctionMode || isAsyncFunctionWrapperParseMode(mode));
2062
        semanticFailIfTrue(m_vm->propertyNames->arguments == *functionInfo.name, "'", functionInfo.name->impl(), "' is not a valid function name in strict mode");
2168
        semanticFailIfTrue(m_vm->propertyNames->arguments == *functionInfo.name, "'", functionInfo.name->impl(), "' is not a valid function name in strict mode");
2063
        semanticFailIfTrue(m_vm->propertyNames->eval == *functionInfo.name, "'", functionInfo.name->impl(), "' is not a valid function name in strict mode");
2169
        semanticFailIfTrue(m_vm->propertyNames->eval == *functionInfo.name, "'", functionInfo.name->impl(), "' is not a valid function name in strict mode");
2064
    }
2170
    }
Lines 2167-2172 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseFunctionDecla a/Source/JavaScriptCore/parser/Parser.cpp_sec25
2167
}
2273
}
2168
2274
2169
template <typename LexerType>
2275
template <typename LexerType>
2276
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseAsyncFunctionDeclaration(TreeBuilder& context, ExportType exportType)
2277
{
2278
    ASSERT(match(FUNCTION));
2279
    JSTokenLocation location(tokenLocation());
2280
    unsigned functionKeywordStart = tokenStart();
2281
    next();
2282
    ParserFunctionInfo<TreeBuilder> functionInfo;
2283
    SourceParseMode parseMode = SourceParseMode::AsyncFunctionMode;
2284
2285
    failIfFalse((parseFunctionInfo(context, FunctionNeedsName, parseMode, true, ConstructorKind::None, SuperBinding::NotNeeded, functionKeywordStart, functionInfo, FunctionDefinitionType::Declaration)), "Cannot parse this async function");
2286
    failIfFalse(functionInfo.name, "Async function statements must have a name");
2287
2288
    std::pair<DeclarationResultMask, ScopeRef> functionDeclaration = declareFunction(functionInfo.name);
2289
    DeclarationResultMask declarationResult = functionDeclaration.first;
2290
    failIfTrueIfStrict(declarationResult & DeclarationResult::InvalidStrictMode, "Cannot declare an async function named '", functionInfo.name->impl(), "' in strict mode");
2291
    if (declarationResult & DeclarationResult::InvalidDuplicateDeclaration)
2292
        internalFailWithMessage(false, "Cannot declare an async function that shadows a let/const/class/function variable '", functionInfo.name->impl(), "' in strict mode");
2293
    if (exportType == ExportType::Exported) {
2294
        semanticFailIfFalse(exportName(*functionInfo.name), "Cannot export a duplicate function name: '", functionInfo.name->impl(), "'");
2295
        currentScope()->moduleScopeData().exportBinding(*functionInfo.name);
2296
    }
2297
2298
    TreeStatement result = context.createFuncDeclStatement(location, functionInfo);
2299
    if (TreeBuilder::CreatesAST)
2300
        functionDeclaration.second->appendFunction(getMetadata(functionInfo));
2301
    return result;
2302
}
2303
2304
template <typename LexerType>
2170
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseClassDeclaration(TreeBuilder& context, ExportType exportType)
2305
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseClassDeclaration(TreeBuilder& context, ExportType exportType)
2171
{
2306
{
2172
    ASSERT(match(CLASSTOKEN));
2307
    ASSERT(match(CLASSTOKEN));
Lines 2247-2252 template <class TreeBuilder> TreeClassExpression Parser<LexerType>::parseClass(T a/Source/JavaScriptCore/parser/Parser.cpp_sec26
2247
2382
2248
        // For backwards compatibility, "static" is a non-reserved keyword in non-strict mode.
2383
        // For backwards compatibility, "static" is a non-reserved keyword in non-strict mode.
2249
        bool isStaticMethod = false;
2384
        bool isStaticMethod = false;
2385
        bool isAsyncMethod = false;
2250
        if (match(RESERVED_IF_STRICT) && *m_token.m_data.ident == m_vm->propertyNames->staticKeyword) {
2386
        if (match(RESERVED_IF_STRICT) && *m_token.m_data.ident == m_vm->propertyNames->staticKeyword) {
2251
            SavePoint savePoint = createSavePoint();
2387
            SavePoint savePoint = createSavePoint();
2252
            next();
2388
            next();
Lines 2257-2262 template <class TreeBuilder> TreeClassExpression Parser<LexerType>::parseClass(T a/Source/JavaScriptCore/parser/Parser.cpp_sec27
2257
                isStaticMethod = true;
2393
                isStaticMethod = true;
2258
        }
2394
        }
2259
2395
2396
        if (match(ASYNC)) {
2397
            SavePoint beforeAsync = createSavePoint();
2398
            next();
2399
            if (!m_lexer->prevTerminator() && (matchIdentifierOrKeyword() || match(STRING) || match(DOUBLE) || match(INTEGER) || match(OPENBRACKET)))
2400
                isAsyncMethod = true;
2401
            else
2402
                restoreSavePoint(beforeAsync);
2403
        }
2404
2260
        // FIXME: Figure out a way to share more code with parseProperty.
2405
        // FIXME: Figure out a way to share more code with parseProperty.
2261
        const CommonIdentifiers& propertyNames = *m_vm->propertyNames;
2406
        const CommonIdentifiers& propertyNames = *m_vm->propertyNames;
2262
        const Identifier* ident = &propertyNames.nullIdentifier;
2407
        const Identifier* ident = &propertyNames.nullIdentifier;
Lines 2265-2271 template <class TreeBuilder> TreeClassExpression Parser<LexerType>::parseClass(T a/Source/JavaScriptCore/parser/Parser.cpp_sec28
2265
        bool isSetter = false;
2410
        bool isSetter = false;
2266
        bool isGenerator = false;
2411
        bool isGenerator = false;
2267
#if ENABLE(ES6_GENERATORS)
2412
#if ENABLE(ES6_GENERATORS)
2268
        if (consume(TIMES))
2413
        if (!isAsyncMethod && consume(TIMES))
2269
            isGenerator = true;
2414
            isGenerator = true;
2270
#endif
2415
#endif
2271
        switch (m_token.m_type) {
2416
        switch (m_token.m_type) {
Lines 2279-2285 template <class TreeBuilder> TreeClassExpression Parser<LexerType>::parseClass(T a/Source/JavaScriptCore/parser/Parser.cpp_sec29
2279
            ident = m_token.m_data.ident;
2424
            ident = m_token.m_data.ident;
2280
            ASSERT(ident);
2425
            ASSERT(ident);
2281
            next();
2426
            next();
2282
            if (!isGenerator && (matchIdentifierOrKeyword() || match(STRING) || match(DOUBLE) || match(INTEGER) || match(OPENBRACKET))) {
2427
            if (!isGenerator && !isAsyncMethod && (matchIdentifierOrKeyword() || match(STRING) || match(DOUBLE) || match(INTEGER) || match(OPENBRACKET))) {
2283
                isGetter = *ident == propertyNames.get;
2428
                isGetter = *ident == propertyNames.get;
2284
                isSetter = *ident == propertyNames.set;
2429
                isSetter = *ident == propertyNames.set;
2285
            }
2430
            }
Lines 2312-2318 template <class TreeBuilder> TreeClassExpression Parser<LexerType>::parseClass(T a/Source/JavaScriptCore/parser/Parser.cpp_sec30
2312
            ParserFunctionInfo<TreeBuilder> methodInfo;
2457
            ParserFunctionInfo<TreeBuilder> methodInfo;
2313
            bool isConstructor = !isStaticMethod && *ident == propertyNames.constructor;
2458
            bool isConstructor = !isStaticMethod && *ident == propertyNames.constructor;
2314
            SourceParseMode parseMode = SourceParseMode::MethodMode;
2459
            SourceParseMode parseMode = SourceParseMode::MethodMode;
2315
            if (isGenerator) {
2460
            if (isAsyncMethod) {
2461
                isConstructor = false;
2462
                parseMode = SourceParseMode::AsyncMethodMode;
2463
                semanticFailIfTrue(*ident == m_vm->propertyNames->prototype, "Cannot declare an async method named 'prototype'");
2464
                semanticFailIfTrue(*ident == m_vm->propertyNames->constructor, "Cannot declare an async method named 'constructor'");
2465
            } else if (isGenerator) {
2316
                isConstructor = false;
2466
                isConstructor = false;
2317
                parseMode = SourceParseMode::GeneratorWrapperFunctionMode;
2467
                parseMode = SourceParseMode::GeneratorWrapperFunctionMode;
2318
                semanticFailIfTrue(*ident == m_vm->propertyNames->prototype, "Cannot declare a generator named 'prototype'");
2468
                semanticFailIfTrue(*ident == m_vm->propertyNames->prototype, "Cannot declare a generator named 'prototype'");
Lines 2394-2402 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseExpressionOrL a/Source/JavaScriptCore/parser/Parser.cpp_sec31
2394
            return context.createExprStatement(location, expression, start, m_lastTokenEndPosition.line);
2544
            return context.createExprStatement(location, expression, start, m_lastTokenEndPosition.line);
2395
        }
2545
        }
2396
        const Identifier* ident = m_token.m_data.ident;
2546
        const Identifier* ident = m_token.m_data.ident;
2547
        const bool isDisallowedLabelAwait = isDisallowedIdentifierAwait(m_token);
2397
        JSTextPosition end = tokenEndPosition();
2548
        JSTextPosition end = tokenEndPosition();
2398
        next();
2549
        next();
2399
        consumeOrFail(COLON, "Labels must be followed by a ':'");
2550
        consumeOrFail(COLON, "Labels must be followed by a ':'");
2551
        semanticFailIfTrue(isDisallowedLabelAwait, "Can't use 'await' as a label ", disallowedIdentifierAwaitReason());
2400
        if (!m_syntaxAlreadyValidated) {
2552
        if (!m_syntaxAlreadyValidated) {
2401
            // This is O(N^2) over the current list of consecutive labels, but I
2553
            // This is O(N^2) over the current list of consecutive labels, but I
2402
            // have never seen more than one label in a row in the real world.
2554
            // have never seen more than one label in a row in the real world.
Lines 2743-2748 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseExportDeclara a/Source/JavaScriptCore/parser/Parser.cpp_sec32
2743
    JSTokenLocation exportLocation(tokenLocation());
2895
    JSTokenLocation exportLocation(tokenLocation());
2744
    next();
2896
    next();
2745
2897
2898
    bool isAsyncFunctionExport = false;
2899
2746
    switch (m_token.m_type) {
2900
    switch (m_token.m_type) {
2747
    case TIMES: {
2901
    case TIMES: {
2748
        // export * FromClause ;
2902
        // export * FromClause ;
Lines 2769-2774 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseExportDeclara a/Source/JavaScriptCore/parser/Parser.cpp_sec33
2769
        const Identifier* localName = nullptr;
2923
        const Identifier* localName = nullptr;
2770
        SavePoint savePoint = createSavePoint();
2924
        SavePoint savePoint = createSavePoint();
2771
2925
2926
        if (UNLIKELY(match(ASYNC))) {
2927
            next();
2928
            if (match(FUNCTION) && !m_lexer->prevTerminator())
2929
                isAsyncFunctionExport = true;
2930
            else
2931
                restoreSavePoint(savePoint);
2932
        }
2933
2772
        bool startsWithFunction = match(FUNCTION);
2934
        bool startsWithFunction = match(FUNCTION);
2773
        if (startsWithFunction
2935
        if (startsWithFunction
2774
#if ENABLE(ES6_CLASS_SYNTAX)
2936
#if ENABLE(ES6_CLASS_SYNTAX)
Lines 2780-2786 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseExportDeclara a/Source/JavaScriptCore/parser/Parser.cpp_sec34
2780
2942
2781
#if ENABLE(ES6_GENERATORS)
2943
#if ENABLE(ES6_GENERATORS)
2782
            // ES6 Generators
2944
            // ES6 Generators
2783
            if (startsWithFunction && match(TIMES))
2945
            if (!isAsyncFunctionExport && startsWithFunction && match(TIMES))
2784
                next();
2946
                next();
2785
#endif
2947
#endif
2786
            if (match(IDENT))
2948
            if (match(IDENT))
Lines 2793-2798 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseExportDeclara a/Source/JavaScriptCore/parser/Parser.cpp_sec35
2793
                DepthManager statementDepth(&m_statementDepth);
2955
                DepthManager statementDepth(&m_statementDepth);
2794
                m_statementDepth = 1;
2956
                m_statementDepth = 1;
2795
                result = parseFunctionDeclaration(context);
2957
                result = parseFunctionDeclaration(context);
2958
            } if (isAsyncFunctionExport) {
2959
                ASSERT(match(ASYNC));
2960
                next();
2961
                DepthManager statementDepth(&m_statementDepth);
2962
                m_statementDepth = 1;
2963
                result = parseAsyncFunctionDeclaration(context);
2796
            }
2964
            }
2797
#if ENABLE(ES6_CLASS_SYNTAX)
2965
#if ENABLE(ES6_CLASS_SYNTAX)
2798
            else {
2966
            else {
Lines 2917-2922 template <class TreeBuilder> TreeStatement Parser<LexerType>::parseExportDeclara a/Source/JavaScriptCore/parser/Parser.cpp_sec36
2917
#endif
3085
#endif
2918
3086
2919
        default:
3087
        default:
3088
            if (UNLIKELY(match(ASYNC))) {
3089
                SavePoint beforeAsync = createSavePoint();
3090
                next();
3091
                if (match(FUNCTION) && !m_lexer->prevTerminator()) {
3092
                    result = parseAsyncFunctionDeclaration(context, ExportType::Exported);
3093
                    break;
3094
                }
3095
                restoreSavePoint(beforeAsync);
3096
            }
2920
            failWithMessage("Expected either a declaration or a variable statement");
3097
            failWithMessage("Expected either a declaration or a variable statement");
2921
            break;
3098
            break;
2922
        }
3099
        }
Lines 2987-2994 template <typename TreeBuilder> TreeExpression Parser<LexerType>::parseAssignmen a/Source/JavaScriptCore/parser/Parser.cpp_sec37
2987
    int initialNonLHSCount = m_parserState.nonLHSCount;
3164
    int initialNonLHSCount = m_parserState.nonLHSCount;
2988
    bool maybeAssignmentPattern = match(OPENBRACE) || match(OPENBRACKET);
3165
    bool maybeAssignmentPattern = match(OPENBRACE) || match(OPENBRACKET);
2989
#if ENABLE(ES6_ARROWFUNCTION_SYNTAX)
3166
#if ENABLE(ES6_ARROWFUNCTION_SYNTAX)
3167
    bool isAsyncArrow = false;
3168
    SavePoint beforeAsyncKeyword = createSavePoint();
3169
    if (UNLIKELY(match(ASYNC))) {
3170
        next();
3171
        if (m_lexer->prevTerminator() || !(match(OPENPAREN) || matchSpecIdentifier()))
3172
            restoreSavePoint(beforeAsyncKeyword);
3173
        else
3174
            isAsyncArrow = true;
3175
    }
3176
2990
    bool wasOpenParen = match(OPENPAREN);
3177
    bool wasOpenParen = match(OPENPAREN);
2991
    bool isValidArrowFunctionStart = match(OPENPAREN) || match(IDENT);
3178
    bool isValidArrowFunctionStart = match(OPENPAREN) || matchSpecIdentifier();
2992
    SavePoint savePoint = createSavePoint();
3179
    SavePoint savePoint = createSavePoint();
2993
    size_t usedVariablesSize;
3180
    size_t usedVariablesSize;
2994
    if (wasOpenParen) {
3181
    if (wasOpenParen) {
Lines 3002-3012 template <typename TreeBuilder> TreeExpression Parser<LexerType>::parseAssignmen a/Source/JavaScriptCore/parser/Parser.cpp_sec38
3002
        return parseYieldExpression(context);
3189
        return parseYieldExpression(context);
3003
#endif
3190
#endif
3004
3191
3192
tryParseConditional:
3005
    TreeExpression lhs = parseConditionalExpression(context);
3193
    TreeExpression lhs = parseConditionalExpression(context);
3006
3194
3007
#if ENABLE(ES6_ARROWFUNCTION_SYNTAX)
3195
#if ENABLE(ES6_ARROWFUNCTION_SYNTAX)
3008
    if (isValidArrowFunctionStart && !match(EOFTOK)) {
3196
    if (isValidArrowFunctionStart && !match(EOFTOK)) {
3009
        bool isArrowFunctionToken = match(ARROWFUNCTION);
3197
        bool isArrowFunctionToken = match(ARROWFUNCTION);
3198
3010
        if (!lhs || isArrowFunctionToken) {
3199
        if (!lhs || isArrowFunctionToken) {
3011
            SavePoint errorRestorationSavePoint = createSavePointForError();
3200
            SavePoint errorRestorationSavePoint = createSavePointForError();
3012
            String oldErrorMessage = m_errorMessage;
3201
            String oldErrorMessage = m_errorMessage;
Lines 3016-3023 template <typename TreeBuilder> TreeExpression Parser<LexerType>::parseAssignmen a/Source/JavaScriptCore/parser/Parser.cpp_sec39
3016
            if (isArrowFunctionParameters()) {
3205
            if (isArrowFunctionParameters()) {
3017
                if (wasOpenParen)
3206
                if (wasOpenParen)
3018
                    currentScope()->revertToPreviousUsedVariables(usedVariablesSize);
3207
                    currentScope()->revertToPreviousUsedVariables(usedVariablesSize);
3019
                return parseArrowFunctionExpression(context);
3208
                return parseArrowFunctionExpression(context, isAsyncArrow);
3020
            }
3209
            }
3210
3211
            if (isAsyncArrow) {
3212
                // Re-parse without skipping over `async` keyword.
3213
                m_errorMessage = String();
3214
                m_lexer->setErrorMessage(String());
3215
                m_lexer->setSawError(false);
3216
                isValidArrowFunctionStart = false;
3217
                isAsyncArrow = false;
3218
                restoreSavePoint(beforeAsyncKeyword);
3219
                goto tryParseConditional;
3220
            }
3221
3021
            restoreSavePointWithError(errorRestorationSavePoint, oldErrorMessage);
3222
            restoreSavePointWithError(errorRestorationSavePoint, oldErrorMessage);
3022
            m_lexer->setErrorMessage(oldLexerErrorMessage);
3223
            m_lexer->setErrorMessage(oldLexerErrorMessage);
3023
            m_lexer->setSawError(hasLexerError);
3224
            m_lexer->setSawError(hasLexerError);
Lines 3149-3154 template <class TreeBuilder> TreeExpression Parser<LexerType>::parseYieldExpress a/Source/JavaScriptCore/parser/Parser.cpp_sec40
3149
}
3350
}
3150
3351
3151
template <typename LexerType>
3352
template <typename LexerType>
3353
template <class TreeBuilder> TreeExpression Parser<LexerType>::parseAwaitExpression(TreeBuilder& context)
3354
{
3355
    // AwaitExpression desugared to YieldExpression
3356
    ASSERT(match(AWAIT));
3357
    ASSERT(currentScope()->isAsyncFunction());
3358
    failIfTrue(m_parserState.functionParsePhase == FunctionParsePhase::Parameters, "Cannot use await expression within parameters");
3359
    JSTokenLocation location(tokenLocation());
3360
    JSTextPosition divotStart = tokenStartPosition();
3361
    next();
3362
    JSTextPosition argumentStart = tokenStartPosition();
3363
    TreeExpression argument = parseUnaryExpression(context);
3364
    failIfFalse(argument, "Failed to parse await expression");
3365
    const bool delegate = false;
3366
    return context.createYield(location, argument, delegate, divotStart, argumentStart, lastTokenEndPosition());
3367
}
3368
3369
template <typename LexerType>
3152
template <class TreeBuilder> TreeExpression Parser<LexerType>::parseConditionalExpression(TreeBuilder& context)
3370
template <class TreeBuilder> TreeExpression Parser<LexerType>::parseConditionalExpression(TreeBuilder& context)
3153
{
3371
{
3154
    JSTokenLocation location(tokenLocation());
3372
    JSTokenLocation location(tokenLocation());
Lines 3232-3242 template <typename LexerType> a/Source/JavaScriptCore/parser/Parser.cpp_sec41
3232
template <class TreeBuilder> TreeProperty Parser<LexerType>::parseProperty(TreeBuilder& context, bool complete)
3450
template <class TreeBuilder> TreeProperty Parser<LexerType>::parseProperty(TreeBuilder& context, bool complete)
3233
{
3451
{
3234
    bool wasIdent = false;
3452
    bool wasIdent = false;
3453
    bool wasAsync = false;
3235
    bool isGenerator = false;
3454
    bool isGenerator = false;
3236
#if ENABLE(ES6_GENERATORS)
3455
#if ENABLE(ES6_GENERATORS)
3237
    if (consume(TIMES))
3456
    if (consume(TIMES))
3238
        isGenerator = true;
3457
        isGenerator = true;
3239
#endif
3458
#endif
3459
3460
    if (UNLIKELY(!isGenerator && match(ASYNC))) {
3461
        SavePoint beforeAsync = createSavePoint();
3462
        next();
3463
        if (!m_lexer->prevTerminator() && (matchIdentifierOrKeyword() || match(STRING) || match(DOUBLE) || match(INTEGER) || match(OPENBRACKET)))
3464
            wasAsync = true;
3465
        else
3466
            restoreSavePoint(beforeAsync);
3467
    }
3468
3240
    switch (m_token.m_type) {
3469
    switch (m_token.m_type) {
3241
    namedProperty:
3470
    namedProperty:
3242
    case IDENT:
3471
    case IDENT:
Lines 3259-3265 template <class TreeBuilder> TreeProperty Parser<LexerType>::parseProperty(TreeB a/Source/JavaScriptCore/parser/Parser.cpp_sec42
3259
        }
3488
        }
3260
3489
3261
        if (match(OPENPAREN)) {
3490
        if (match(OPENPAREN)) {
3262
            auto method = parsePropertyMethod(context, ident, isGenerator);
3491
            auto method = parsePropertyMethod(context, ident, isGenerator, wasAsync);
3263
            propagateError();
3492
            propagateError();
3264
            return context.createProperty(ident, method, PropertyNode::Constant, PropertyNode::KnownDirect, complete);
3493
            return context.createProperty(ident, method, PropertyNode::Constant, PropertyNode::KnownDirect, complete);
3265
        }
3494
        }
Lines 3296-3302 template <class TreeBuilder> TreeProperty Parser<LexerType>::parseProperty(TreeB a/Source/JavaScriptCore/parser/Parser.cpp_sec43
3296
3525
3297
        if (match(OPENPAREN)) {
3526
        if (match(OPENPAREN)) {
3298
            const Identifier& ident = m_parserArena.identifierArena().makeNumericIdentifier(const_cast<VM*>(m_vm), propertyName);
3527
            const Identifier& ident = m_parserArena.identifierArena().makeNumericIdentifier(const_cast<VM*>(m_vm), propertyName);
3299
            auto method = parsePropertyMethod(context, &ident, isGenerator);
3528
            auto method = parsePropertyMethod(context, &ident, isGenerator, wasAsync);
3300
            propagateError();
3529
            propagateError();
3301
            return context.createProperty(&ident, method, PropertyNode::Constant, PropertyNode::Unknown, complete);
3530
            return context.createProperty(&ident, method, PropertyNode::Constant, PropertyNode::Unknown, complete);
3302
        }
3531
        }
Lines 3315-3321 template <class TreeBuilder> TreeProperty Parser<LexerType>::parseProperty(TreeB a/Source/JavaScriptCore/parser/Parser.cpp_sec44
3315
        handleProductionOrFail(CLOSEBRACKET, "]", "end", "computed property name");
3544
        handleProductionOrFail(CLOSEBRACKET, "]", "end", "computed property name");
3316
3545
3317
        if (match(OPENPAREN)) {
3546
        if (match(OPENPAREN)) {
3318
            auto method = parsePropertyMethod(context, &m_vm->propertyNames->nullIdentifier, isGenerator);
3547
            auto method = parsePropertyMethod(context, &m_vm->propertyNames->nullIdentifier, isGenerator, wasAsync);
3319
            propagateError();
3548
            propagateError();
3320
            return context.createProperty(propertyName, method, static_cast<PropertyNode::Type>(PropertyNode::Constant | PropertyNode::Computed), PropertyNode::KnownDirect, complete);
3549
            return context.createProperty(propertyName, method, static_cast<PropertyNode::Type>(PropertyNode::Constant | PropertyNode::Computed), PropertyNode::KnownDirect, complete);
3321
        }
3550
        }
Lines 3334-3345 template <class TreeBuilder> TreeProperty Parser<LexerType>::parseProperty(TreeB a/Source/JavaScriptCore/parser/Parser.cpp_sec45
3334
}
3563
}
3335
3564
3336
template <typename LexerType>
3565
template <typename LexerType>
3337
template <class TreeBuilder> TreeExpression Parser<LexerType>::parsePropertyMethod(TreeBuilder& context, const Identifier* methodName, bool isGenerator)
3566
template <class TreeBuilder> TreeExpression Parser<LexerType>::parsePropertyMethod(TreeBuilder& context, const Identifier* methodName, bool isGenerator, bool isAsync)
3338
{
3567
{
3339
    JSTokenLocation methodLocation(tokenLocation());
3568
    JSTokenLocation methodLocation(tokenLocation());
3340
    unsigned methodStart = tokenStart();
3569
    unsigned methodStart = tokenStart();
3341
    ParserFunctionInfo<TreeBuilder> methodInfo;
3570
    ParserFunctionInfo<TreeBuilder> methodInfo;
3342
    SourceParseMode parseMode = isGenerator ? SourceParseMode::GeneratorWrapperFunctionMode : SourceParseMode::MethodMode;
3571
    SourceParseMode parseMode = isGenerator ? SourceParseMode::GeneratorWrapperFunctionMode : isAsync ? SourceParseMode::AsyncMethodMode : SourceParseMode::MethodMode;
3343
    failIfFalse((parseFunctionInfo(context, FunctionNoRequirements, parseMode, false, ConstructorKind::None, SuperBinding::NotNeeded, methodStart, methodInfo, FunctionDefinitionType::Method)), "Cannot parse this method");
3572
    failIfFalse((parseFunctionInfo(context, FunctionNoRequirements, parseMode, false, ConstructorKind::None, SuperBinding::NotNeeded, methodStart, methodInfo, FunctionDefinitionType::Method)), "Cannot parse this method");
3344
    methodInfo.name = methodName;
3573
    methodInfo.name = methodName;
3345
    return context.createMethodDefinition(methodLocation, methodInfo);
3574
    return context.createMethodDefinition(methodLocation, methodInfo);
Lines 3599-3604 template <class TreeBuilder> TreeExpression Parser<LexerType>::parseFunctionExpr a/Source/JavaScriptCore/parser/Parser.cpp_sec46
3599
}
3828
}
3600
3829
3601
template <typename LexerType>
3830
template <typename LexerType>
3831
template <class TreeBuilder> TreeExpression Parser<LexerType>::parseAsyncFunctionExpression(TreeBuilder& context)
3832
{
3833
    ASSERT(match(FUNCTION));
3834
    JSTokenLocation location(tokenLocation());
3835
    unsigned functionKeywordStart = tokenStart();
3836
    next();
3837
    ParserFunctionInfo<TreeBuilder> functionInfo;
3838
    functionInfo.name = &m_vm->propertyNames->nullIdentifier;
3839
    SourceParseMode parseMode = SourceParseMode::AsyncFunctionMode;
3840
    failIfFalse(parseFunctionInfo(context, FunctionNoRequirements, parseMode, false, ConstructorKind::None, SuperBinding::NotNeeded, functionKeywordStart, functionInfo, FunctionDefinitionType::Expression), "Cannot parse async function expression");
3841
    return context.createFunctionExpr(location, functionInfo);
3842
}
3843
3844
template <typename LexerType>
3602
template <class TreeBuilder> typename TreeBuilder::TemplateString Parser<LexerType>::parseTemplateString(TreeBuilder& context, bool isTemplateHead, typename LexerType::RawStringsBuildMode rawStringsBuildMode, bool& elementIsTail)
3845
template <class TreeBuilder> typename TreeBuilder::TemplateString Parser<LexerType>::parseTemplateString(TreeBuilder& context, bool isTemplateHead, typename LexerType::RawStringsBuildMode rawStringsBuildMode, bool& elementIsTail)
3603
{
3846
{
3604
    if (!isTemplateHead) {
3847
    if (!isTemplateHead) {
Lines 3690-3695 template <class TreeBuilder> TreeExpression Parser<LexerType>::parsePrimaryExpre a/Source/JavaScriptCore/parser/Parser.cpp_sec47
3690
            currentScope()->setInnerArrowFunctionUsesThis();
3933
            currentScope()->setInnerArrowFunctionUsesThis();
3691
        return context.createThisExpr(location, m_thisTDZMode);
3934
        return context.createThisExpr(location, m_thisTDZMode);
3692
    }
3935
    }
3936
    case AWAIT:
3693
    case IDENT: {
3937
    case IDENT: {
3694
    identifierExpression:
3938
    identifierExpression:
3695
        JSTextPosition start = tokenStartPosition();
3939
        JSTextPosition start = tokenStartPosition();
Lines 3761-3766 template <class TreeBuilder> TreeExpression Parser<LexerType>::parsePrimaryExpre a/Source/JavaScriptCore/parser/Parser.cpp_sec48
3761
        if (!strictMode() && !currentScope()->isGenerator())
4005
        if (!strictMode() && !currentScope()->isGenerator())
3762
            goto identifierExpression;
4006
            goto identifierExpression;
3763
        failDueToUnexpectedToken();
4007
        failDueToUnexpectedToken();
4008
    case ASYNC: {
4009
        SavePoint beforeAsync = createSavePoint();
4010
        next();
4011
        if (match(FUNCTION) && !m_lexer->prevTerminator())
4012
            return parseAsyncFunctionExpression(context);
4013
        restoreSavePoint(beforeAsync);
4014
        goto identifierExpression;
4015
    }
3764
    case LET:
4016
    case LET:
3765
        if (!strictMode())
4017
        if (!strictMode())
3766
            goto identifierExpression;
4018
            goto identifierExpression;
Lines 3961-3967 endMemberExpression: a/Source/JavaScriptCore/parser/Parser.cpp_sec49
3961
}
4213
}
3962
4214
3963
template <typename LexerType>
4215
template <typename LexerType>
3964
template <class TreeBuilder> TreeExpression Parser<LexerType>::parseArrowFunctionExpression(TreeBuilder& context)
4216
template <class TreeBuilder> TreeExpression Parser<LexerType>::parseArrowFunctionExpression(TreeBuilder& context, bool isAsync)
3965
{
4217
{
3966
    JSTokenLocation location;
4218
    JSTokenLocation location;
3967
4219
Lines 3969-3975 template <class TreeBuilder> TreeExpression Parser<LexerType>::parseArrowFunctio a/Source/JavaScriptCore/parser/Parser.cpp_sec50
3969
    location = tokenLocation();
4221
    location = tokenLocation();
3970
    ParserFunctionInfo<TreeBuilder> info;
4222
    ParserFunctionInfo<TreeBuilder> info;
3971
    info.name = &m_vm->propertyNames->nullIdentifier;
4223
    info.name = &m_vm->propertyNames->nullIdentifier;
3972
    failIfFalse((parseFunctionInfo(context, FunctionNoRequirements, SourceParseMode::ArrowFunctionMode, true, ConstructorKind::None, SuperBinding::NotNeeded, functionKeywordStart, info, FunctionDefinitionType::Expression)), "Cannot parse arrow function expression");
4224
    SourceParseMode parseMode = isAsync ? SourceParseMode::AsyncArrowFunctionMode : SourceParseMode::ArrowFunctionMode;
4225
4226
    failIfFalse((parseFunctionInfo(context, FunctionNoRequirements, parseMode, true, ConstructorKind::None, SuperBinding::NotNeeded, functionKeywordStart, info, FunctionDefinitionType::Expression)), "Cannot parse arrow function expression");
3973
4227
3974
    return context.createArrowFunctionExpr(location, info);
4228
    return context.createArrowFunctionExpr(location, info);
3975
}
4229
}
Lines 4013-4018 template <class TreeBuilder> TreeExpression Parser<LexerType>::parseUnaryExpress a/Source/JavaScriptCore/parser/Parser.cpp_sec51
4013
    bool modifiesExpr = false;
4267
    bool modifiesExpr = false;
4014
    bool requiresLExpr = false;
4268
    bool requiresLExpr = false;
4015
    unsigned lastOperator = 0;
4269
    unsigned lastOperator = 0;
4270
4271
    if (match(AWAIT) && !isAWAITMaskedAsIDENT())
4272
        return parseAwaitExpression(context);
4273
4016
    while (isUnaryOp(m_token.m_type)) {
4274
    while (isUnaryOp(m_token.m_type)) {
4017
        if (strictMode()) {
4275
        if (strictMode()) {
4018
            switch (m_token.m_type) {
4276
            switch (m_token.m_type) {
- a/Source/JavaScriptCore/parser/Parser.h -7 / +120 lines
Lines 155-161 struct Scope { a/Source/JavaScriptCore/parser/Parser.h_sec1
155
    WTF_MAKE_NONCOPYABLE(Scope);
155
    WTF_MAKE_NONCOPYABLE(Scope);
156
156
157
public:
157
public:
158
    Scope(const VM* vm, bool isFunction, bool isGenerator, bool strictMode, bool isArrowFunction)
158
    Scope(const VM* vm, bool isFunction, bool isGenerator, bool strictMode, bool isArrowFunction, bool isAsyncFunction)
159
        : m_vm(vm)
159
        : m_vm(vm)
160
        , m_shadowsArguments(false)
160
        , m_shadowsArguments(false)
161
        , m_usesEval(false)
161
        , m_usesEval(false)
Lines 170-175 public: a/Source/JavaScriptCore/parser/Parser.h_sec2
170
        , m_isGeneratorBoundary(false)
170
        , m_isGeneratorBoundary(false)
171
        , m_isArrowFunction(isArrowFunction)
171
        , m_isArrowFunction(isArrowFunction)
172
        , m_isArrowFunctionBoundary(false)
172
        , m_isArrowFunctionBoundary(false)
173
        , m_isAsyncFunction(isAsyncFunction)
174
        , m_isAsyncFunctionBoundary(false)
173
        , m_isLexicalScope(false)
175
        , m_isLexicalScope(false)
174
        , m_isFunctionBoundary(false)
176
        , m_isFunctionBoundary(false)
175
        , m_isValidStrictMode(true)
177
        , m_isValidStrictMode(true)
Lines 258-263 public: a/Source/JavaScriptCore/parser/Parser.h_sec3
258
    void setSourceParseMode(SourceParseMode mode)
260
    void setSourceParseMode(SourceParseMode mode)
259
    {
261
    {
260
        switch (mode) {
262
        switch (mode) {
263
        case SourceParseMode::AsyncArrowFunctionBodyMode:
264
            setIsAsyncArrowFunctionBody();
265
            break;
266
267
        case SourceParseMode::AsyncFunctionBodyMode:
268
            setIsAsyncFunctionBody();
269
            break;
270
261
        case SourceParseMode::GeneratorBodyMode:
271
        case SourceParseMode::GeneratorBodyMode:
262
            setIsGenerator();
272
            setIsGenerator();
263
            break;
273
            break;
Lines 277-282 public: a/Source/JavaScriptCore/parser/Parser.h_sec4
277
            setIsArrowFunction();
287
            setIsArrowFunction();
278
            break;
288
            break;
279
289
290
        case SourceParseMode::AsyncFunctionMode:
291
        case SourceParseMode::AsyncMethodMode:
292
            setIsAsyncFunction();
293
            break;
294
295
        case SourceParseMode::AsyncArrowFunctionMode:
296
            setIsAsyncArrowFunction();
297
            break;
298
280
        case SourceParseMode::ProgramMode:
299
        case SourceParseMode::ProgramMode:
281
            break;
300
            break;
282
301
Lines 291-296 public: a/Source/JavaScriptCore/parser/Parser.h_sec5
291
    bool isFunctionBoundary() const { return m_isFunctionBoundary; }
310
    bool isFunctionBoundary() const { return m_isFunctionBoundary; }
292
    bool isGenerator() const { return m_isGenerator; }
311
    bool isGenerator() const { return m_isGenerator; }
293
    bool isGeneratorBoundary() const { return m_isGeneratorBoundary; }
312
    bool isGeneratorBoundary() const { return m_isGeneratorBoundary; }
313
    bool isAsyncFunction() const { return m_isAsyncFunction; }
314
    bool isAsyncFunctionBoundary() const { return m_isAsyncFunctionBoundary; }
294
315
295
    bool hasArguments() const { return m_hasArguments; }
316
    bool hasArguments() const { return m_hasArguments; }
296
317
Lines 320-325 public: a/Source/JavaScriptCore/parser/Parser.h_sec6
320
        return *m_moduleScopeData;
341
        return *m_moduleScopeData;
321
    }
342
    }
322
343
344
    bool isModule() const
345
    {
346
        return !!m_moduleScopeData;
347
    }
348
323
    void computeLexicallyCapturedVariablesAndPurgeCandidates()
349
    void computeLexicallyCapturedVariablesAndPurgeCandidates()
324
    {
350
    {
325
        // Because variables may be defined at any time in the range of a lexical scope, we must
351
        // Because variables may be defined at any time in the range of a lexical scope, we must
Lines 682-687 private: a/Source/JavaScriptCore/parser/Parser.h_sec7
682
        m_isGeneratorBoundary = false;
708
        m_isGeneratorBoundary = false;
683
        m_isArrowFunctionBoundary = false;
709
        m_isArrowFunctionBoundary = false;
684
        m_isArrowFunction = false;
710
        m_isArrowFunction = false;
711
        m_isAsyncFunctionBoundary = false;
712
        m_isAsyncFunction = false;
685
    }
713
    }
686
714
687
    void setIsGeneratorFunction()
715
    void setIsGeneratorFunction()
Lines 705-710 private: a/Source/JavaScriptCore/parser/Parser.h_sec8
705
        m_isArrowFunction = true;
733
        m_isArrowFunction = true;
706
    }
734
    }
707
735
736
    void setIsAsyncArrowFunction()
737
    {
738
        setIsArrowFunction();
739
        m_isAsyncFunction = true;
740
    }
741
742
    void setIsAsyncFunction()
743
    {
744
        setIsFunction();
745
        m_isAsyncFunction = true;
746
    }
747
748
    void setIsAsyncFunctionBody()
749
    {
750
        setIsFunction();
751
        m_hasArguments = false;
752
        m_isAsyncFunction = true;
753
        m_isAsyncFunctionBoundary = true;
754
    }
755
756
    void setIsAsyncArrowFunctionBody()
757
    {
758
        setIsArrowFunction();
759
        m_hasArguments = false;
760
        m_isAsyncFunction = true;
761
        m_isAsyncFunctionBoundary = true;
762
    }
763
708
    void setIsModule()
764
    void setIsModule()
709
    {
765
    {
710
        m_moduleScopeData = ModuleScopeData::create();
766
        m_moduleScopeData = ModuleScopeData::create();
Lines 724-729 private: a/Source/JavaScriptCore/parser/Parser.h_sec9
724
    bool m_isGeneratorBoundary;
780
    bool m_isGeneratorBoundary;
725
    bool m_isArrowFunction;
781
    bool m_isArrowFunction;
726
    bool m_isArrowFunctionBoundary;
782
    bool m_isArrowFunctionBoundary;
783
    bool m_isAsyncFunction;
784
    bool m_isAsyncFunctionBoundary;
727
    bool m_isLexicalScope;
785
    bool m_isLexicalScope;
728
    bool m_isFunctionBoundary;
786
    bool m_isFunctionBoundary;
729
    bool m_isValidStrictMode;
787
    bool m_isValidStrictMode;
Lines 811-816 private: a/Source/JavaScriptCore/parser/Parser.h_sec10
811
        bool m_oldAllowsIn;
869
        bool m_oldAllowsIn;
812
    };
870
    };
813
871
872
    struct AllowAwaitOverride {
873
        AllowAwaitOverride(Parser* parser, bool value)
874
            : m_parser(parser)
875
            , m_oldAllowsAwait(parser->m_allowsAwait)
876
        {
877
            parser->m_allowsAwait = value;
878
        }
879
        ~AllowAwaitOverride()
880
        {
881
            m_parser->m_allowsAwait = m_oldAllowsAwait;
882
        }
883
        Parser* m_parser;
884
        bool m_oldAllowsAwait;
885
    };
886
814
    struct AutoPopScopeRef : public ScopeRef {
887
    struct AutoPopScopeRef : public ScopeRef {
815
        AutoPopScopeRef(Parser* parser, ScopeRef scope)
888
        AutoPopScopeRef(Parser* parser, ScopeRef scope)
816
        : ScopeRef(scope)
889
        : ScopeRef(scope)
Lines 948-953 private: a/Source/JavaScriptCore/parser/Parser.h_sec11
948
        return DestructuringKind::DestructureToVariables;
1021
        return DestructuringKind::DestructureToVariables;
949
    }
1022
    }
950
1023
1024
    ALWAYS_INLINE const char* declarationTypeToVariableKind(DeclarationType type)
1025
    {
1026
        switch (type) {
1027
        case DeclarationType::VarDeclaration:
1028
            return "variable name";
1029
        case DeclarationType::LetDeclaration:
1030
        case DeclarationType::ConstDeclaration:
1031
            return "lexical variable name";
1032
        }
1033
        RELEASE_ASSERT_NOT_REACHED();
1034
        return "invalid";
1035
    }
1036
951
    ALWAYS_INLINE AssignmentContext assignmentContextFromDeclarationType(DeclarationType type)
1037
    ALWAYS_INLINE AssignmentContext assignmentContextFromDeclarationType(DeclarationType type)
952
    {
1038
    {
953
        switch (type) {
1039
        switch (type) {
Lines 1004-1010 private: a/Source/JavaScriptCore/parser/Parser.h_sec12
1004
    {
1090
    {
1005
        unsigned i = m_scopeStack.size() - 1;
1091
        unsigned i = m_scopeStack.size() - 1;
1006
        ASSERT(i < m_scopeStack.size() && m_scopeStack.size());
1092
        ASSERT(i < m_scopeStack.size() && m_scopeStack.size());
1007
        while (i && (!m_scopeStack[i].isFunctionBoundary() || m_scopeStack[i].isGeneratorBoundary() || m_scopeStack[i].isArrowFunctionBoundary()))
1093
        while (i && (!m_scopeStack[i].isFunctionBoundary() || m_scopeStack[i].isGeneratorBoundary() || m_scopeStack[i].isArrowFunctionBoundary() || m_scopeStack[i].isAsyncFunctionBoundary()))
1008
            i--;
1094
            i--;
1009
        return ScopeRef(&m_scopeStack, i);
1095
        return ScopeRef(&m_scopeStack, i);
1010
    }
1096
    }
Lines 1015-1027 private: a/Source/JavaScriptCore/parser/Parser.h_sec13
1015
        bool isStrict = false;
1101
        bool isStrict = false;
1016
        bool isGenerator = false;
1102
        bool isGenerator = false;
1017
        bool isArrowFunction = false;
1103
        bool isArrowFunction = false;
1104
        bool isAsyncFunction = false;
1018
        if (!m_scopeStack.isEmpty()) {
1105
        if (!m_scopeStack.isEmpty()) {
1019
            isStrict = m_scopeStack.last().strictMode();
1106
            isStrict = m_scopeStack.last().strictMode();
1020
            isFunction = m_scopeStack.last().isFunction();
1107
            isFunction = m_scopeStack.last().isFunction();
1021
            isGenerator = m_scopeStack.last().isGenerator();
1108
            isGenerator = m_scopeStack.last().isGenerator();
1022
            isArrowFunction = m_scopeStack.last().isArrowFunction();
1109
            isArrowFunction = m_scopeStack.last().isArrowFunction();
1110
            isAsyncFunction = m_scopeStack.last().isAsyncFunction();
1023
        }
1111
        }
1024
        m_scopeStack.constructAndAppend(m_vm, isFunction, isGenerator, isStrict, isArrowFunction);
1112
        m_scopeStack.constructAndAppend(m_vm, isFunction, isGenerator, isStrict, isArrowFunction, isAsyncFunction);
1025
        return currentScope();
1113
        return currentScope();
1026
    }
1114
    }
1027
1115
Lines 1033-1039 private: a/Source/JavaScriptCore/parser/Parser.h_sec14
1033
        
1121
        
1034
        if (m_scopeStack.last().isArrowFunction())
1122
        if (m_scopeStack.last().isArrowFunction())
1035
            m_scopeStack.last().setInnerArrowFunctionUsesEvalAndUseArgumentsIfNeeded();
1123
            m_scopeStack.last().setInnerArrowFunctionUsesEvalAndUseArgumentsIfNeeded();
1036
        
1124
1037
        if (!(m_scopeStack.last().isFunctionBoundary() && !m_scopeStack.last().isArrowFunctionBoundary()))
1125
        if (!(m_scopeStack.last().isFunctionBoundary() && !m_scopeStack.last().isArrowFunctionBoundary()))
1038
            m_scopeStack[m_scopeStack.size() - 2].mergeInnerArrowFunctionFeatures(m_scopeStack.last().innerArrowFunctionFeatures());
1126
            m_scopeStack[m_scopeStack.size() - 2].mergeInnerArrowFunctionFeatures(m_scopeStack.last().innerArrowFunctionFeatures());
1039
1127
Lines 1316-1325 private: a/Source/JavaScriptCore/parser/Parser.h_sec15
1316
        return match(YIELD) && !strictMode() && !inGenerator;
1404
        return match(YIELD) && !strictMode() && !inGenerator;
1317
    }
1405
    }
1318
1406
1407
    ALWAYS_INLINE bool isAWAITMaskedAsIDENT()
1408
    {
1409
        return match(AWAIT) && !currentFunctionScope()->isAsyncFunction();
1410
    }
1411
1319
    // http://ecma-international.org/ecma-262/6.0/#sec-generator-function-definitions-static-semantics-early-errors
1412
    // http://ecma-international.org/ecma-262/6.0/#sec-generator-function-definitions-static-semantics-early-errors
1320
    ALWAYS_INLINE bool matchSpecIdentifier(bool inGenerator)
1413
    ALWAYS_INLINE bool matchSpecIdentifier(bool inGenerator)
1321
    {
1414
    {
1322
        return match(IDENT) || isLETMaskedAsIDENT() || isYIELDMaskedAsIDENT(inGenerator);
1415
        return match(IDENT) || isLETMaskedAsIDENT() || isYIELDMaskedAsIDENT(inGenerator) || match(AWAIT);
1323
    }
1416
    }
1324
1417
1325
    ALWAYS_INLINE bool matchSpecIdentifier()
1418
    ALWAYS_INLINE bool matchSpecIdentifier()
Lines 1329-1339 private: a/Source/JavaScriptCore/parser/Parser.h_sec16
1329
1422
1330
    template <class TreeBuilder> TreeSourceElements parseSourceElements(TreeBuilder&, SourceElementsMode);
1423
    template <class TreeBuilder> TreeSourceElements parseSourceElements(TreeBuilder&, SourceElementsMode);
1331
    template <class TreeBuilder> TreeSourceElements parseGeneratorFunctionSourceElements(TreeBuilder&, SourceElementsMode);
1424
    template <class TreeBuilder> TreeSourceElements parseGeneratorFunctionSourceElements(TreeBuilder&, SourceElementsMode);
1425
    template <class TreeBuilder> TreeSourceElements parseAsyncFunctionSourceElements(TreeBuilder&, SourceParseMode, bool isArrowFunctionBodyExpression, SourceElementsMode);
1332
    template <class TreeBuilder> TreeStatement parseStatementListItem(TreeBuilder&, const Identifier*& directive, unsigned* directiveLiteralLength);
1426
    template <class TreeBuilder> TreeStatement parseStatementListItem(TreeBuilder&, const Identifier*& directive, unsigned* directiveLiteralLength);
1333
    template <class TreeBuilder> TreeStatement parseStatement(TreeBuilder&, const Identifier*& directive, unsigned* directiveLiteralLength = 0);
1427
    template <class TreeBuilder> TreeStatement parseStatement(TreeBuilder&, const Identifier*& directive, unsigned* directiveLiteralLength = 0);
1334
    enum class ExportType { Exported, NotExported };
1428
    enum class ExportType { Exported, NotExported };
1335
    template <class TreeBuilder> TreeStatement parseClassDeclaration(TreeBuilder&, ExportType = ExportType::NotExported);
1429
    template <class TreeBuilder> TreeStatement parseClassDeclaration(TreeBuilder&, ExportType = ExportType::NotExported);
1336
    template <class TreeBuilder> TreeStatement parseFunctionDeclaration(TreeBuilder&, ExportType = ExportType::NotExported);
1430
    template <class TreeBuilder> TreeStatement parseFunctionDeclaration(TreeBuilder&, ExportType = ExportType::NotExported);
1431
    template <class TreeBuilder> TreeStatement parseAsyncFunctionDeclaration(TreeBuilder&, ExportType = ExportType::NotExported);
1337
    template <class TreeBuilder> TreeStatement parseVariableDeclaration(TreeBuilder&, DeclarationType, ExportType = ExportType::NotExported);
1432
    template <class TreeBuilder> TreeStatement parseVariableDeclaration(TreeBuilder&, DeclarationType, ExportType = ExportType::NotExported);
1338
    template <class TreeBuilder> TreeStatement parseDoWhileStatement(TreeBuilder&);
1433
    template <class TreeBuilder> TreeStatement parseDoWhileStatement(TreeBuilder&);
1339
    template <class TreeBuilder> TreeStatement parseWhileStatement(TreeBuilder&);
1434
    template <class TreeBuilder> TreeStatement parseWhileStatement(TreeBuilder&);
Lines 1360-1382 private: a/Source/JavaScriptCore/parser/Parser.h_sec17
1360
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseConditionalExpression(TreeBuilder&);
1455
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseConditionalExpression(TreeBuilder&);
1361
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseBinaryExpression(TreeBuilder&);
1456
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseBinaryExpression(TreeBuilder&);
1362
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseUnaryExpression(TreeBuilder&);
1457
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseUnaryExpression(TreeBuilder&);
1458
    template <class TreeBuilder> NEVER_INLINE TreeExpression parseAwaitExpression(TreeBuilder&);
1363
    template <class TreeBuilder> TreeExpression parseMemberExpression(TreeBuilder&);
1459
    template <class TreeBuilder> TreeExpression parseMemberExpression(TreeBuilder&);
1364
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parsePrimaryExpression(TreeBuilder&);
1460
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parsePrimaryExpression(TreeBuilder&);
1365
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseArrayLiteral(TreeBuilder&);
1461
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseArrayLiteral(TreeBuilder&);
1366
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseObjectLiteral(TreeBuilder&);
1462
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseObjectLiteral(TreeBuilder&);
1367
    template <class TreeBuilder> NEVER_INLINE TreeExpression parseStrictObjectLiteral(TreeBuilder&);
1463
    template <class TreeBuilder> NEVER_INLINE TreeExpression parseStrictObjectLiteral(TreeBuilder&);
1368
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseFunctionExpression(TreeBuilder&);
1464
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseFunctionExpression(TreeBuilder&);
1465
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseAsyncFunctionExpression(TreeBuilder&);
1369
    template <class TreeBuilder> ALWAYS_INLINE TreeArguments parseArguments(TreeBuilder&);
1466
    template <class TreeBuilder> ALWAYS_INLINE TreeArguments parseArguments(TreeBuilder&);
1370
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseArgument(TreeBuilder&, ArgumentType&);
1467
    template <class TreeBuilder> ALWAYS_INLINE TreeExpression parseArgument(TreeBuilder&, ArgumentType&);
1371
    template <class TreeBuilder> TreeProperty parseProperty(TreeBuilder&, bool strict);
1468
    template <class TreeBuilder> TreeProperty parseProperty(TreeBuilder&, bool strict);
1372
    template <class TreeBuilder> TreeExpression parsePropertyMethod(TreeBuilder& context, const Identifier* methodName, bool isGenerator);
1469
    template <class TreeBuilder> TreeExpression parsePropertyMethod(TreeBuilder& context, const Identifier* methodName, bool isGenerator, bool isAsyncMethod);
1373
    template <class TreeBuilder> TreeProperty parseGetterSetter(TreeBuilder&, bool strict, PropertyNode::Type, unsigned getterOrSetterStartOffset, ConstructorKind = ConstructorKind::None, SuperBinding = SuperBinding::NotNeeded);
1470
    template <class TreeBuilder> TreeProperty parseGetterSetter(TreeBuilder&, bool strict, PropertyNode::Type, unsigned getterOrSetterStartOffset, ConstructorKind = ConstructorKind::None, SuperBinding = SuperBinding::NotNeeded);
1374
    template <class TreeBuilder> ALWAYS_INLINE TreeFunctionBody parseFunctionBody(TreeBuilder&, const JSTokenLocation&, int, int functionKeywordStart, int functionNameStart, int parametersStart, ConstructorKind, SuperBinding, FunctionBodyType, unsigned, SourceParseMode);
1471
    template <class TreeBuilder> ALWAYS_INLINE TreeFunctionBody parseFunctionBody(TreeBuilder&, const JSTokenLocation&, int, int functionKeywordStart, int functionNameStart, int parametersStart, ConstructorKind, SuperBinding, FunctionBodyType, unsigned, SourceParseMode);
1375
    template <class TreeBuilder> ALWAYS_INLINE bool parseFormalParameters(TreeBuilder&, TreeFormalParameterList, unsigned&);
1472
    template <class TreeBuilder> ALWAYS_INLINE bool parseFormalParameters(TreeBuilder&, TreeFormalParameterList, unsigned&);
1376
    enum VarDeclarationListContext { ForLoopContext, VarDeclarationContext };
1473
    enum VarDeclarationListContext { ForLoopContext, VarDeclarationContext };
1377
    template <class TreeBuilder> TreeExpression parseVariableDeclarationList(TreeBuilder&, int& declarations, TreeDestructuringPattern& lastPattern, TreeExpression& lastInitializer, JSTextPosition& identStart, JSTextPosition& initStart, JSTextPosition& initEnd, VarDeclarationListContext, DeclarationType, ExportType, bool& forLoopConstDoesNotHaveInitializer);
1474
    template <class TreeBuilder> TreeExpression parseVariableDeclarationList(TreeBuilder&, int& declarations, TreeDestructuringPattern& lastPattern, TreeExpression& lastInitializer, JSTextPosition& identStart, JSTextPosition& initStart, JSTextPosition& initEnd, VarDeclarationListContext, DeclarationType, ExportType, bool& forLoopConstDoesNotHaveInitializer);
1378
    template <class TreeBuilder> TreeSourceElements parseArrowFunctionSingleExpressionBodySourceElements(TreeBuilder&);
1475
    template <class TreeBuilder> TreeSourceElements parseArrowFunctionSingleExpressionBodySourceElements(TreeBuilder&);
1379
    template <class TreeBuilder> TreeExpression parseArrowFunctionExpression(TreeBuilder&);
1476
    template <class TreeBuilder> TreeExpression parseArrowFunctionExpression(TreeBuilder&, bool isAsync);
1380
    template <class TreeBuilder> NEVER_INLINE TreeDestructuringPattern createBindingPattern(TreeBuilder&, DestructuringKind, ExportType, const Identifier&, JSToken, AssignmentContext, const Identifier** duplicateIdentifier);
1477
    template <class TreeBuilder> NEVER_INLINE TreeDestructuringPattern createBindingPattern(TreeBuilder&, DestructuringKind, ExportType, const Identifier&, JSToken, AssignmentContext, const Identifier** duplicateIdentifier);
1381
    template <class TreeBuilder> NEVER_INLINE TreeDestructuringPattern createAssignmentElement(TreeBuilder&, TreeExpression&, const JSTextPosition&, const JSTextPosition&);
1478
    template <class TreeBuilder> NEVER_INLINE TreeDestructuringPattern createAssignmentElement(TreeBuilder&, TreeExpression&, const JSTextPosition&, const JSTextPosition&);
1382
    template <class TreeBuilder> NEVER_INLINE TreeDestructuringPattern parseBindingOrAssignmentElement(TreeBuilder& context, DestructuringKind, ExportType, const Identifier** duplicateIdentifier, bool* hasDestructuringPattern, AssignmentContext bindingContext, int depth);
1479
    template <class TreeBuilder> NEVER_INLINE TreeDestructuringPattern parseBindingOrAssignmentElement(TreeBuilder& context, DestructuringKind, ExportType, const Identifier** duplicateIdentifier, bool* hasDestructuringPattern, AssignmentContext bindingContext, int depth);
Lines 1439-1444 private: a/Source/JavaScriptCore/parser/Parser.h_sec18
1439
        return !m_errorMessage.isNull();
1536
        return !m_errorMessage.isNull();
1440
    }
1537
    }
1441
1538
1539
    bool isDisallowedIdentifierAwait(const JSToken& token)
1540
    {
1541
        return token.m_type == AWAIT && (currentScope()->isAsyncFunctionBoundary() || currentScope()->isModule() || !m_allowsAwait);
1542
    }
1543
1544
    const char* disallowedIdentifierAwaitReason()
1545
    {
1546
        if (!m_allowsAwait || currentScope()->isAsyncFunctionBoundary())
1547
            return "in an async function";
1548
        if (currentScope()->isModule())
1549
            return "in a module";
1550
        ASSERT(false);
1551
        return "(unknown)";
1552
    }
1553
1442
    enum class FunctionParsePhase { Parameters, Body };
1554
    enum class FunctionParsePhase { Parameters, Body };
1443
    struct ParserState {
1555
    struct ParserState {
1444
        int assignmentCount { 0 };
1556
        int assignmentCount { 0 };
Lines 1533-1538 private: a/Source/JavaScriptCore/parser/Parser.h_sec19
1533
    String m_errorMessage;
1645
    String m_errorMessage;
1534
    JSToken m_token;
1646
    JSToken m_token;
1535
    bool m_allowsIn;
1647
    bool m_allowsIn;
1648
    bool m_allowsAwait;
1536
    JSTextPosition m_lastTokenEndPosition;
1649
    JSTextPosition m_lastTokenEndPosition;
1537
    bool m_syntaxAlreadyValidated;
1650
    bool m_syntaxAlreadyValidated;
1538
    int m_statementDepth;
1651
    int m_statementDepth;
- a/Source/JavaScriptCore/parser/ParserModes.h +125 lines
Lines 52-57 enum class SourceParseMode : uint8_t { a/Source/JavaScriptCore/parser/ParserModes.h_sec1
52
    SetterMode,
52
    SetterMode,
53
    MethodMode,
53
    MethodMode,
54
    ArrowFunctionMode,
54
    ArrowFunctionMode,
55
    AsyncFunctionBodyMode,
56
    AsyncArrowFunctionBodyMode,
57
    AsyncFunctionMode,
58
    AsyncMethodMode,
59
    AsyncArrowFunctionMode,
55
    ProgramMode,
60
    ProgramMode,
56
    ModuleAnalyzeMode,
61
    ModuleAnalyzeMode,
57
    ModuleEvaluateMode
62
    ModuleEvaluateMode
Lines 67-72 inline bool isFunctionParseMode(SourceParseMode parseMode) a/Source/JavaScriptCore/parser/ParserModes.h_sec2
67
    case SourceParseMode::SetterMode:
72
    case SourceParseMode::SetterMode:
68
    case SourceParseMode::MethodMode:
73
    case SourceParseMode::MethodMode:
69
    case SourceParseMode::ArrowFunctionMode:
74
    case SourceParseMode::ArrowFunctionMode:
75
    case SourceParseMode::AsyncFunctionBodyMode:
76
    case SourceParseMode::AsyncFunctionMode:
77
    case SourceParseMode::AsyncMethodMode:
78
    case SourceParseMode::AsyncArrowFunctionMode:
79
    case SourceParseMode::AsyncArrowFunctionBodyMode:
70
        return true;
80
        return true;
71
81
72
    case SourceParseMode::ProgramMode:
82
    case SourceParseMode::ProgramMode:
Lines 78-83 inline bool isFunctionParseMode(SourceParseMode parseMode) a/Source/JavaScriptCore/parser/ParserModes.h_sec3
78
    return false;
88
    return false;
79
}
89
}
80
90
91
inline bool isAsyncFunctionParseMode(SourceParseMode parseMode)
92
{
93
    switch (parseMode) {
94
    case SourceParseMode::AsyncFunctionBodyMode:
95
    case SourceParseMode::AsyncArrowFunctionBodyMode:
96
    case SourceParseMode::AsyncFunctionMode:
97
    case SourceParseMode::AsyncMethodMode:
98
    case SourceParseMode::AsyncArrowFunctionMode:
99
        return true;
100
101
    case SourceParseMode::NormalFunctionMode:
102
    case SourceParseMode::GeneratorBodyMode:
103
    case SourceParseMode::GeneratorWrapperFunctionMode:
104
    case SourceParseMode::GetterMode:
105
    case SourceParseMode::SetterMode:
106
    case SourceParseMode::MethodMode:
107
    case SourceParseMode::ArrowFunctionMode:
108
    case SourceParseMode::ModuleAnalyzeMode:
109
    case SourceParseMode::ModuleEvaluateMode:
110
    case SourceParseMode::ProgramMode:
111
        return false;
112
    }
113
    RELEASE_ASSERT_NOT_REACHED();
114
    return false;
115
}
116
117
inline bool isAsyncArrowFunctionParseMode(SourceParseMode parseMode)
118
{
119
    switch (parseMode) {
120
    case SourceParseMode::AsyncArrowFunctionMode:
121
    case SourceParseMode::AsyncArrowFunctionBodyMode:
122
        return true;
123
124
    case SourceParseMode::NormalFunctionMode:
125
    case SourceParseMode::GeneratorBodyMode:
126
    case SourceParseMode::GeneratorWrapperFunctionMode:
127
    case SourceParseMode::GetterMode:
128
    case SourceParseMode::SetterMode:
129
    case SourceParseMode::MethodMode:
130
    case SourceParseMode::ArrowFunctionMode:
131
    case SourceParseMode::ModuleAnalyzeMode:
132
    case SourceParseMode::ModuleEvaluateMode:
133
    case SourceParseMode::AsyncFunctionBodyMode:
134
    case SourceParseMode::AsyncMethodMode:
135
    case SourceParseMode::AsyncFunctionMode:
136
    case SourceParseMode::ProgramMode:
137
        return false;
138
    }
139
140
    RELEASE_ASSERT_NOT_REACHED();
141
    return false;
142
}
143
144
inline bool isAsyncFunctionWrapperParseMode(SourceParseMode parseMode)
145
{
146
    switch (parseMode) {
147
    case SourceParseMode::AsyncFunctionMode:
148
    case SourceParseMode::AsyncMethodMode:
149
    case SourceParseMode::AsyncArrowFunctionMode:
150
        return true;
151
152
    case SourceParseMode::AsyncFunctionBodyMode:
153
    case SourceParseMode::AsyncArrowFunctionBodyMode:
154
    case SourceParseMode::NormalFunctionMode:
155
    case SourceParseMode::GeneratorBodyMode:
156
    case SourceParseMode::GeneratorWrapperFunctionMode:
157
    case SourceParseMode::GetterMode:
158
    case SourceParseMode::SetterMode:
159
    case SourceParseMode::MethodMode:
160
    case SourceParseMode::ArrowFunctionMode:
161
    case SourceParseMode::ModuleAnalyzeMode:
162
    case SourceParseMode::ModuleEvaluateMode:
163
    case SourceParseMode::ProgramMode:
164
        return false;
165
    }
166
    RELEASE_ASSERT_NOT_REACHED();
167
    return false;
168
}
169
170
inline bool isAsyncFunctionBodyParseMode(SourceParseMode parseMode)
171
{
172
    switch (parseMode) {
173
    case SourceParseMode::AsyncFunctionBodyMode:
174
    case SourceParseMode::AsyncArrowFunctionBodyMode:
175
        return true;
176
177
    case SourceParseMode::NormalFunctionMode:
178
    case SourceParseMode::GeneratorBodyMode:
179
    case SourceParseMode::GeneratorWrapperFunctionMode:
180
    case SourceParseMode::GetterMode:
181
    case SourceParseMode::SetterMode:
182
    case SourceParseMode::MethodMode:
183
    case SourceParseMode::ArrowFunctionMode:
184
    case SourceParseMode::AsyncFunctionMode:
185
    case SourceParseMode::AsyncMethodMode:
186
    case SourceParseMode::AsyncArrowFunctionMode:
187
    case SourceParseMode::ModuleAnalyzeMode:
188
    case SourceParseMode::ModuleEvaluateMode:
189
    case SourceParseMode::ProgramMode:
190
        return false;
191
    }
192
    RELEASE_ASSERT_NOT_REACHED();
193
    return false;
194
}
195
81
inline bool isModuleParseMode(SourceParseMode parseMode)
196
inline bool isModuleParseMode(SourceParseMode parseMode)
82
{
197
{
83
    switch (parseMode) {
198
    switch (parseMode) {
Lines 92-97 inline bool isModuleParseMode(SourceParseMode parseMode) a/Source/JavaScriptCore/parser/ParserModes.h_sec4
92
    case SourceParseMode::SetterMode:
207
    case SourceParseMode::SetterMode:
93
    case SourceParseMode::MethodMode:
208
    case SourceParseMode::MethodMode:
94
    case SourceParseMode::ArrowFunctionMode:
209
    case SourceParseMode::ArrowFunctionMode:
210
    case SourceParseMode::AsyncFunctionBodyMode:
211
    case SourceParseMode::AsyncFunctionMode:
212
    case SourceParseMode::AsyncMethodMode:
213
    case SourceParseMode::AsyncArrowFunctionMode:
214
    case SourceParseMode::AsyncArrowFunctionBodyMode:
95
    case SourceParseMode::ProgramMode:
215
    case SourceParseMode::ProgramMode:
96
        return false;
216
        return false;
97
    }
217
    }
Lines 112-117 inline bool isProgramParseMode(SourceParseMode parseMode) a/Source/JavaScriptCore/parser/ParserModes.h_sec5
112
    case SourceParseMode::SetterMode:
232
    case SourceParseMode::SetterMode:
113
    case SourceParseMode::MethodMode:
233
    case SourceParseMode::MethodMode:
114
    case SourceParseMode::ArrowFunctionMode:
234
    case SourceParseMode::ArrowFunctionMode:
235
    case SourceParseMode::AsyncFunctionBodyMode:
236
    case SourceParseMode::AsyncFunctionMode:
237
    case SourceParseMode::AsyncMethodMode:
238
    case SourceParseMode::AsyncArrowFunctionMode:
239
    case SourceParseMode::AsyncArrowFunctionBodyMode:
115
    case SourceParseMode::ModuleAnalyzeMode:
240
    case SourceParseMode::ModuleAnalyzeMode:
116
    case SourceParseMode::ModuleEvaluateMode:
241
    case SourceParseMode::ModuleEvaluateMode:
117
        return false;
242
        return false;
- a/Source/JavaScriptCore/parser/ParserTokens.h +2 lines
Lines 79-84 enum JSTokenType { a/Source/JavaScriptCore/parser/ParserTokens.h_sec1
79
    IMPORT,
79
    IMPORT,
80
    EXPORT,
80
    EXPORT,
81
    YIELD,
81
    YIELD,
82
    AWAIT,
83
    ASYNC,
82
    CLASSTOKEN,
84
    CLASSTOKEN,
83
    EXTENDS,
85
    EXTENDS,
84
    SUPER,
86
    SUPER,
- a/Source/JavaScriptCore/runtime/AsyncFunctionConstructor.cpp +77 lines
Line 0 a/Source/JavaScriptCore/runtime/AsyncFunctionConstructor.cpp_sec1
1
/*
2
 * Copyright (C) 2016 Caitlin Potter <caitp@igalia.com>.
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 * 1. Redistributions of source code must retain the above copyright
8
 *    notice, this list of conditions and the following disclaimer.
9
 * 2. Redistributions in binary form must reproduce the above copyright
10
 *    notice, this list of conditions and the following disclaimer in the
11
 *    documentation and/or other materials provided with the distribution.
12
 *
13
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23
 * THE POSSIBILITY OF SUCH DAMAGE.
24
 */
25
26
#include "config.h"
27
#include "AsyncFunctionConstructor.h"
28
29
#include "AsyncFunctionPrototype.h"
30
#include "FunctionConstructor.h"
31
#include "JSCInlines.h"
32
33
namespace JSC {
34
35
STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(AsyncFunctionConstructor);
36
37
const ClassInfo AsyncFunctionConstructor::s_info = { "AsyncFunction", &Base::s_info, nullptr, CREATE_METHOD_TABLE(AsyncFunctionConstructor) };
38
39
AsyncFunctionConstructor::AsyncFunctionConstructor(VM& vm, Structure* structure)
40
    : InternalFunction(vm, structure)
41
{
42
}
43
44
void AsyncFunctionConstructor::finishCreation(VM& vm, AsyncFunctionPrototype* asyncFunctionPrototype)
45
{
46
    Base::finishCreation(vm, "AsyncFunction");
47
    putDirectWithoutTransition(vm, vm.propertyNames->prototype, asyncFunctionPrototype, DontEnum | DontDelete | ReadOnly);
48
49
    // Number of arguments for constructor
50
    putDirectWithoutTransition(vm, vm.propertyNames->length, jsNumber(1), ReadOnly | DontDelete | DontEnum);
51
}
52
53
static EncodedJSValue JSC_HOST_CALL callAsyncFunctionConstructor(ExecState* exec)
54
{
55
    ArgList args(exec);
56
    return JSValue::encode(constructFunction(exec, asInternalFunction(exec->callee())->globalObject(), args, FunctionConstructionMode::Async));
57
}
58
59
static EncodedJSValue JSC_HOST_CALL constructAsyncFunctionConstructor(ExecState* exec)
60
{
61
    ArgList args(exec);
62
    return JSValue::encode(constructFunction(exec, asInternalFunction(exec->callee())->globalObject(), args, FunctionConstructionMode::Async));
63
}
64
65
CallType AsyncFunctionConstructor::getCallData(JSCell*, CallData& callData)
66
{
67
    callData.native.function = callAsyncFunctionConstructor;
68
    return CallType::Host;
69
}
70
71
ConstructType AsyncFunctionConstructor::getConstructData(JSCell*, ConstructData& constructData)
72
{
73
    constructData.native.function = constructAsyncFunctionConstructor;
74
    return ConstructType::Host;
75
}
76
77
} // namespace JSC
- a/Source/JavaScriptCore/runtime/AsyncFunctionConstructor.h +66 lines
Line 0 a/Source/JavaScriptCore/runtime/AsyncFunctionConstructor.h_sec1
1
/*
2
 * Copyright (C) 2016 Caitlin Potter <caitp@igalia.com>.
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 * 1. Redistributions of source code must retain the above copyright
8
 *    notice, this list of conditions and the following disclaimer.
9
 * 2. Redistributions in binary form must reproduce the above copyright
10
 *    notice, this list of conditions and the following disclaimer in the
11
 *    documentation and/or other materials provided with the distribution.
12
 *
13
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23
 * THE POSSIBILITY OF SUCH DAMAGE.
24
 */
25
26
#ifndef AsyncFunctionConstructor_h
27
#define AsyncFunctionConstructor_h
28
29
#include "InternalFunction.h"
30
31
namespace WTF {
32
class TextPosition;
33
}
34
35
namespace JSC {
36
37
class AsyncFunctionPrototype;
38
39
class AsyncFunctionConstructor : public InternalFunction {
40
public:
41
    typedef InternalFunction Base;
42
43
    static AsyncFunctionConstructor* create(VM& vm, Structure* structure, AsyncFunctionPrototype* asyncFunctionPrototype)
44
    {
45
        AsyncFunctionConstructor* constructor = new (NotNull, allocateCell<AsyncFunctionConstructor>(vm.heap)) AsyncFunctionConstructor(vm, structure);
46
        constructor->finishCreation(vm, asyncFunctionPrototype);
47
        return constructor;
48
    }
49
50
    DECLARE_INFO;
51
52
    static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
53
    {
54
        return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
55
    }
56
57
private:
58
    AsyncFunctionConstructor(VM&, Structure*);
59
    void finishCreation(VM&, AsyncFunctionPrototype*);
60
    static ConstructType getConstructData(JSCell*, ConstructData&);
61
    static CallType getCallData(JSCell*, CallData&);
62
};
63
64
} // namespace JSC
65
66
#endif // AsyncFunctionConstructor_h
- a/Source/JavaScriptCore/runtime/AsyncFunctionPrototype.cpp +56 lines
Line 0 a/Source/JavaScriptCore/runtime/AsyncFunctionPrototype.cpp_sec1
1
/*
2
 * Copyright (C) 2016 Caitlin Potter <caitp@igalia.com>.
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 * 1. Redistributions of source code must retain the above copyright
8
 *    notice, this list of conditions and the following disclaimer.
9
 * 2. Redistributions in binary form must reproduce the above copyright
10
 *    notice, this list of conditions and the following disclaimer in the
11
 *    documentation and/or other materials provided with the distribution.
12
 *
13
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23
 * THE POSSIBILITY OF SUCH DAMAGE.
24
 */
25
26
#include "config.h"
27
#include "AsyncFunctionPrototype.h"
28
29
#include "BuiltinExecutables.h"
30
#include "BuiltinNames.h"
31
#include "Error.h"
32
#include "JSArray.h"
33
#include "JSCInlines.h"
34
#include "JSFunction.h"
35
#include "JSString.h"
36
#include "JSStringBuilder.h"
37
#include "Lexer.h"
38
39
namespace JSC {
40
41
STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(AsyncFunctionPrototype);
42
43
const ClassInfo AsyncFunctionPrototype::s_info = { "AsyncFunction", &Base::s_info, nullptr, CREATE_METHOD_TABLE(AsyncFunctionPrototype) };
44
45
AsyncFunctionPrototype::AsyncFunctionPrototype(VM& vm, Structure* structure)
46
    : JSNonFinalObject(vm, structure)
47
{
48
}
49
50
void AsyncFunctionPrototype::finishCreation(VM& vm)
51
{
52
    Base::finishCreation(vm);
53
    putDirectWithoutTransition(vm, vm.propertyNames->length, jsNumber(0), DontDelete | ReadOnly | DontEnum);
54
}
55
56
} // namespace JSC
- a/Source/JavaScriptCore/runtime/AsyncFunctionPrototype.h +60 lines
Line 0 a/Source/JavaScriptCore/runtime/AsyncFunctionPrototype.h_sec1
1
/*
2
 * Copyright (C) 2016 Caitlin Potter <caitp@igalia.com>.
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 * 1. Redistributions of source code must retain the above copyright
8
 *    notice, this list of conditions and the following disclaimer.
9
 * 2. Redistributions in binary form must reproduce the above copyright
10
 *    notice, this list of conditions and the following disclaimer in the
11
 *    documentation and/or other materials provided with the distribution.
12
 *
13
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23
 * THE POSSIBILITY OF SUCH DAMAGE.
24
 */
25
26
#ifndef AsyncFunctionPrototype_h
27
#define AsyncFunctionPrototype_h
28
29
#include "JSObject.h"
30
31
namespace JSC {
32
33
class AsyncFunctionPrototype : public JSNonFinalObject {
34
public:
35
    typedef JSNonFinalObject Base;
36
37
    static AsyncFunctionPrototype* create(VM& vm, Structure* structure)
38
    {
39
        AsyncFunctionPrototype* prototype = new (NotNull, allocateCell<AsyncFunctionPrototype>(vm.heap)) AsyncFunctionPrototype(vm, structure);
40
        prototype->finishCreation(vm);
41
        return prototype;
42
    }
43
44
    static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto)
45
    {
46
        return Structure::create(vm, globalObject, proto, TypeInfo(ObjectType, StructureFlags), info());
47
    }
48
49
    DECLARE_INFO;
50
51
protected:
52
    void finishCreation(VM&);
53
54
private:
55
    AsyncFunctionPrototype(VM&, Structure*);
56
};
57
58
} // namespace JSC
59
60
#endif // AsyncFunctionPrototype_h
- a/Source/JavaScriptCore/runtime/CodeCache.cpp -1 / +4 lines
Lines 191-197 UnlinkedFunctionExecutable* CodeCache::getFunctionExecutableFromGlobalCode(VM& v a/Source/JavaScriptCore/runtime/CodeCache.cpp_sec1
191
    metadata->setEndPosition(positionBeforeLastNewline);
191
    metadata->setEndPosition(positionBeforeLastNewline);
192
    // The Function constructor only has access to global variables, so no variables will be under TDZ.
192
    // The Function constructor only has access to global variables, so no variables will be under TDZ.
193
    VariableEnvironment emptyTDZVariables;
193
    VariableEnvironment emptyTDZVariables;
194
    UnlinkedFunctionExecutable* functionExecutable = UnlinkedFunctionExecutable::create(&vm, source, metadata, UnlinkedNormalFunction, ConstructAbility::CanConstruct, emptyTDZVariables, DerivedContextType::None);
194
    ConstructAbility constructAbility = ConstructAbility::CanConstruct;
195
    if (isAsyncFunctionParseMode(metadata->parseMode()))
196
        constructAbility = ConstructAbility::CannotConstruct;
197
    UnlinkedFunctionExecutable* functionExecutable = UnlinkedFunctionExecutable::create(&vm, source, metadata, UnlinkedNormalFunction, constructAbility, emptyTDZVariables, DerivedContextType::None);
195
198
196
    m_sourceCode.addCache(key, SourceCodeValue(vm, functionExecutable, m_sourceCode.age()));
199
    m_sourceCode.addCache(key, SourceCodeValue(vm, functionExecutable, m_sourceCode.age()));
197
    return functionExecutable;
200
    return functionExecutable;
- a/Source/JavaScriptCore/runtime/CommonIdentifiers.h +3 lines
Lines 31-36 a/Source/JavaScriptCore/runtime/CommonIdentifiers.h_sec1
31
    macro(Array) \
31
    macro(Array) \
32
    macro(ArrayBuffer) \
32
    macro(ArrayBuffer) \
33
    macro(ArrayIterator) \
33
    macro(ArrayIterator) \
34
    macro(AsyncFunction) \
34
    macro(BYTES_PER_ELEMENT) \
35
    macro(BYTES_PER_ELEMENT) \
35
    macro(Boolean) \
36
    macro(Boolean) \
36
    macro(Collator) \
37
    macro(Collator) \
Lines 225-230 a/Source/JavaScriptCore/runtime/CommonIdentifiers.h_sec2
225
    macro(year)
226
    macro(year)
226
227
227
#define JSC_COMMON_IDENTIFIERS_EACH_KEYWORD(macro) \
228
#define JSC_COMMON_IDENTIFIERS_EACH_KEYWORD(macro) \
229
    macro(async) \
230
    macro(await) \
228
    macro(break) \
231
    macro(break) \
229
    macro(case) \
232
    macro(case) \
230
    macro(catch) \
233
    macro(catch) \
- a/Source/JavaScriptCore/runtime/FunctionConstructor.cpp -5 / +9 lines
Lines 95-108 JSObject* constructFunctionSkippingEvalEnabledCheck( a/Source/JavaScriptCore/runtime/FunctionConstructor.cpp_sec1
95
    // See https://bugs.webkit.org/show_bug.cgi?id=24350.
95
    // See https://bugs.webkit.org/show_bug.cgi?id=24350.
96
    String program;
96
    String program;
97
    if (args.isEmpty())
97
    if (args.isEmpty())
98
        program = makeString("{function ", functionConstructionMode == FunctionConstructionMode::Generator ? "*" : "", functionName.string(), "() {\n\n}}");
98
        program = makeString("{", functionConstructionMode == FunctionConstructionMode::Async ? "async function " : "function ", functionConstructionMode == FunctionConstructionMode::Generator ? "*" : "", functionName.string(), "() {\n\n}}");
99
    else if (args.size() == 1)
99
    else if (args.size() == 1)
100
        program = makeString("{function ", functionConstructionMode == FunctionConstructionMode::Generator ? "*" : "", functionName.string(), "() {\n", args.at(0).toString(exec)->value(exec), "\n}}");
100
        program = makeString("{", functionConstructionMode == FunctionConstructionMode::Async ? "async function " : "function ", functionConstructionMode == FunctionConstructionMode::Generator ? "*" : "", functionName.string(), "() {\n", args.at(0).toString(exec)->value(exec), "\n}}");
101
    else {
101
    else {
102
        StringBuilder builder;
102
        StringBuilder builder;
103
        builder.appendLiteral("{function ");
103
        if (functionConstructionMode == FunctionConstructionMode::Async)
104
        if (functionConstructionMode == FunctionConstructionMode::Generator)
104
            builder.appendLiteral("{async function ");
105
            builder.append('*');
105
        else {
106
            builder.appendLiteral("{function ");
107
            if (functionConstructionMode == FunctionConstructionMode::Generator)
108
                builder.append('*');
109
        }
106
        builder.append(functionName.string());
110
        builder.append(functionName.string());
107
        builder.append('(');
111
        builder.append('(');
108
        builder.append(args.at(0).toString(exec)->view(exec).get());
112
        builder.append(args.at(0).toString(exec)->view(exec).get());
- a/Source/JavaScriptCore/runtime/FunctionConstructor.h +1 lines
Lines 59-64 private: a/Source/JavaScriptCore/runtime/FunctionConstructor.h_sec1
59
enum class FunctionConstructionMode {
59
enum class FunctionConstructionMode {
60
    Function,
60
    Function,
61
    Generator,
61
    Generator,
62
    Async
62
};
63
};
63
64
64
JSObject* constructFunction(ExecState*, JSGlobalObject*, const ArgList&, const Identifier& functionName, const String& sourceURL, const WTF::TextPosition&, FunctionConstructionMode = FunctionConstructionMode::Function, JSValue newTarget = JSValue());
65
JSObject* constructFunction(ExecState*, JSGlobalObject*, const ArgList&, const Identifier& functionName, const String& sourceURL, const WTF::TextPosition&, FunctionConstructionMode = FunctionConstructionMode::Function, JSValue newTarget = JSValue());
- a/Source/JavaScriptCore/runtime/JSAsyncFunction.cpp +69 lines
Line 0 a/Source/JavaScriptCore/runtime/JSAsyncFunction.cpp_sec1
1
/*
2
 * Copyright (C) 2016 Caitlin Potter <caitp@igalia.com>.
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 * 1. Redistributions of source code must retain the above copyright
8
 *    notice, this list of conditions and the following disclaimer.
9
 * 2. Redistributions in binary form must reproduce the above copyright
10
 *    notice, this list of conditions and the following disclaimer in the
11
 *    documentation and/or other materials provided with the distribution.
12
 *
13
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23
 * THE POSSIBILITY OF SUCH DAMAGE.
24
 */
25
26
#include "config.h"
27
#include "JSAsyncFunction.h"
28
29
#include "Error.h"
30
#include "JSCInlines.h"
31
#include "JSCJSValue.h"
32
#include "JSFunction.h"
33
#include "JSFunctionInlines.h"
34
#include "JSObject.h"
35
#include "PropertySlot.h"
36
#include "VM.h"
37
38
namespace JSC {
39
40
const ClassInfo JSAsyncFunction::s_info = { "AsyncFunction", &Base::s_info, nullptr, CREATE_METHOD_TABLE(JSAsyncFunction) };
41
42
JSAsyncFunction::JSAsyncFunction(VM& vm, FunctionExecutable* executable, JSScope* scope)
43
    : Base(vm, executable, scope, scope->globalObject()->asyncFunctionStructure())
44
{
45
}
46
47
JSAsyncFunction* JSAsyncFunction::createImpl(VM& vm, FunctionExecutable* executable, JSScope* scope)
48
{
49
    JSAsyncFunction* asyncFunction = new (NotNull, allocateCell<JSAsyncFunction>(vm.heap)) JSAsyncFunction(vm, executable, scope);
50
    ASSERT(asyncFunction->structure()->globalObject());
51
    asyncFunction->finishCreation(vm);
52
    return asyncFunction;
53
}
54
55
JSAsyncFunction* JSAsyncFunction::create(VM& vm, FunctionExecutable* executable, JSScope* scope)
56
{
57
    JSAsyncFunction* asyncFunction = createImpl(vm, executable, scope);
58
    executable->singletonFunction()->notifyWrite(vm, asyncFunction, "Allocating an async function");
59
    return asyncFunction;
60
}
61
62
JSAsyncFunction* JSAsyncFunction::createWithInvalidatedReallocationWatchpoint(VM& vm, FunctionExecutable* executable, JSScope* scope)
63
{
64
    return createImpl(vm, executable, scope);
65
}
66
67
} // namespace JSC
68
69
- a/Source/JavaScriptCore/runtime/JSAsyncFunction.h +76 lines
Line 0 a/Source/JavaScriptCore/runtime/JSAsyncFunction.h_sec1
1
/*
2
 * Copyright (C) 2016 Caitlin Potter <caitp@igalia.com>.
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 * 1. Redistributions of source code must retain the above copyright
8
 *    notice, this list of conditions and the following disclaimer.
9
 * 2. Redistributions in binary form must reproduce the above copyright
10
 *    notice, this list of conditions and the following disclaimer in the
11
 *    documentation and/or other materials provided with the distribution.
12
 *
13
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23
 * THE POSSIBILITY OF SUCH DAMAGE.
24
 */
25
26
#ifndef JSAsyncFunction_h
27
#define JSAsyncFunction_h
28
29
#include "JSFunction.h"
30
31
namespace JSC {
32
33
class JSGlobalObject;
34
class LLIntOffsetsExtractor;
35
class LLIntDesiredOffsets;
36
37
class JSAsyncFunction : public JSFunction {
38
    friend class JIT;
39
#if ENABLE(DFG_JIT)
40
    friend class DFG::SpeculativeJIT;
41
    friend class DFG::JITCompiler;
42
#endif
43
    friend class VM;
44
public:
45
    typedef JSFunction Base;
46
47
    const static unsigned StructureFlags = Base::StructureFlags;
48
49
    DECLARE_EXPORT_INFO;
50
51
    static JSAsyncFunction* create(VM&, FunctionExecutable*, JSScope*);
52
    static JSAsyncFunction* createWithInvalidatedReallocationWatchpoint(VM&, FunctionExecutable*, JSScope*);
53
54
    static size_t allocationSize(size_t inlineCapacity)
55
    {
56
        ASSERT_UNUSED(inlineCapacity, !inlineCapacity);
57
        return sizeof(JSAsyncFunction);
58
    }
59
60
    static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
61
    {
62
        ASSERT(globalObject);
63
        return Structure::create(vm, globalObject, prototype, TypeInfo(JSFunctionType, StructureFlags), info());
64
    }
65
66
private:
67
    JSAsyncFunction(VM&, FunctionExecutable*, JSScope*);
68
69
    static JSAsyncFunction* createImpl(VM&, FunctionExecutable*, JSScope*);
70
71
    friend class LLIntOffsetsExtractor;
72
};
73
74
} // namespace JSC
75
76
#endif // JSAsyncFunction_h
- a/Source/JavaScriptCore/runtime/JSGlobalObject.cpp +10 lines
Lines 33-38 a/Source/JavaScriptCore/runtime/JSGlobalObject.cpp_sec1
33
#include "ArrayConstructor.h"
33
#include "ArrayConstructor.h"
34
#include "ArrayIteratorPrototype.h"
34
#include "ArrayIteratorPrototype.h"
35
#include "ArrayPrototype.h"
35
#include "ArrayPrototype.h"
36
#include "AsyncFunctionConstructor.h"
37
#include "AsyncFunctionPrototype.h"
36
#include "BooleanConstructor.h"
38
#include "BooleanConstructor.h"
37
#include "BooleanPrototype.h"
39
#include "BooleanPrototype.h"
38
#include "BuiltinNames.h"
40
#include "BuiltinNames.h"
Lines 63-68 a/Source/JavaScriptCore/runtime/JSGlobalObject.cpp_sec2
63
#include "JSArrayBufferConstructor.h"
65
#include "JSArrayBufferConstructor.h"
64
#include "JSArrayBufferPrototype.h"
66
#include "JSArrayBufferPrototype.h"
65
#include "JSArrayIterator.h"
67
#include "JSArrayIterator.h"
68
#include "JSAsyncFunction.h"
66
#include "JSBoundFunction.h"
69
#include "JSBoundFunction.h"
67
#include "JSBoundSlotBaseFunction.h"
70
#include "JSBoundSlotBaseFunction.h"
68
#include "JSCInlines.h"
71
#include "JSCInlines.h"
Lines 440-445 m_ ## lowerName ## Prototype->putDirectWithoutTransition(vm, vm.propertyNames->c a/Source/JavaScriptCore/runtime/JSGlobalObject.cpp_sec3
440
    m_typeErrorConstructor.set(vm, this, NativeErrorConstructor::create(vm, this, nativeErrorStructure, nativeErrorPrototypeStructure, ASCIILiteral("TypeError")));
443
    m_typeErrorConstructor.set(vm, this, NativeErrorConstructor::create(vm, this, nativeErrorStructure, nativeErrorPrototypeStructure, ASCIILiteral("TypeError")));
441
    m_URIErrorConstructor.set(vm, this, NativeErrorConstructor::create(vm, this, nativeErrorStructure, nativeErrorPrototypeStructure, ASCIILiteral("URIError")));
444
    m_URIErrorConstructor.set(vm, this, NativeErrorConstructor::create(vm, this, nativeErrorStructure, nativeErrorPrototypeStructure, ASCIILiteral("URIError")));
442
445
446
    m_asyncFunctionPrototype.set(vm, this, AsyncFunctionPrototype::create(vm, AsyncFunctionPrototype::createStructure(vm, this, m_functionPrototype.get())));
447
    AsyncFunctionConstructor* asyncFunctionConstructor = AsyncFunctionConstructor::create(vm, AsyncFunctionConstructor::createStructure(vm, this, functionConstructor), m_asyncFunctionPrototype.get());
448
    m_asyncFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, asyncFunctionConstructor, DontEnum);
449
    m_asyncFunctionStructure.set(vm, this, JSAsyncFunction::createStructure(vm, this, m_asyncFunctionPrototype.get()));
450
443
    m_generatorFunctionPrototype.set(vm, this, GeneratorFunctionPrototype::create(vm, GeneratorFunctionPrototype::createStructure(vm, this, m_functionPrototype.get())));
451
    m_generatorFunctionPrototype.set(vm, this, GeneratorFunctionPrototype::create(vm, GeneratorFunctionPrototype::createStructure(vm, this, m_functionPrototype.get())));
444
    GeneratorFunctionConstructor* generatorFunctionConstructor = GeneratorFunctionConstructor::create(vm, GeneratorFunctionConstructor::createStructure(vm, this, functionConstructor), m_generatorFunctionPrototype.get());
452
    GeneratorFunctionConstructor* generatorFunctionConstructor = GeneratorFunctionConstructor::create(vm, GeneratorFunctionConstructor::createStructure(vm, this, functionConstructor), m_generatorFunctionPrototype.get());
445
    m_generatorFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, generatorFunctionConstructor, DontEnum);
453
    m_generatorFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, generatorFunctionConstructor, DontEnum);
Lines 455-460 m_ ## lowerName ## Prototype->putDirectWithoutTransition(vm, vm.propertyNames->c a/Source/JavaScriptCore/runtime/JSGlobalObject.cpp_sec4
455
    
463
    
456
    putDirectWithoutTransition(vm, vm.propertyNames->Object, objectConstructor, DontEnum);
464
    putDirectWithoutTransition(vm, vm.propertyNames->Object, objectConstructor, DontEnum);
457
    putDirectWithoutTransition(vm, vm.propertyNames->Function, functionConstructor, DontEnum);
465
    putDirectWithoutTransition(vm, vm.propertyNames->Function, functionConstructor, DontEnum);
466
    putDirectWithoutTransition(vm, vm.propertyNames->AsyncFunction, asyncFunctionConstructor, DontEnum);
458
    putDirectWithoutTransition(vm, vm.propertyNames->Array, arrayConstructor, DontEnum);
467
    putDirectWithoutTransition(vm, vm.propertyNames->Array, arrayConstructor, DontEnum);
459
    putDirectWithoutTransition(vm, vm.propertyNames->RegExp, m_regExpConstructor.get(), DontEnum);
468
    putDirectWithoutTransition(vm, vm.propertyNames->RegExp, m_regExpConstructor.get(), DontEnum);
460
    putDirectWithoutTransition(vm, vm.propertyNames->EvalError, m_evalErrorConstructor.get(), DontEnum);
469
    putDirectWithoutTransition(vm, vm.propertyNames->EvalError, m_evalErrorConstructor.get(), DontEnum);
Lines 600-605 putDirectWithoutTransition(vm, vm.propertyNames-> jsName, lowerName ## Construct a/Source/JavaScriptCore/runtime/JSGlobalObject.cpp_sec5
600
        GlobalPropertyInfo(vm.propertyNames->MapPrivateName, mapConstructor, DontEnum | DontDelete | ReadOnly),
609
        GlobalPropertyInfo(vm.propertyNames->MapPrivateName, mapConstructor, DontEnum | DontDelete | ReadOnly),
601
        GlobalPropertyInfo(vm.propertyNames->builtinNames().generatorResumePrivateName(), JSFunction::createBuiltinFunction(vm, generatorPrototypeGeneratorResumeCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
610
        GlobalPropertyInfo(vm.propertyNames->builtinNames().generatorResumePrivateName(), JSFunction::createBuiltinFunction(vm, generatorPrototypeGeneratorResumeCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
602
        GlobalPropertyInfo(vm.propertyNames->builtinNames().thisTimeValuePrivateName(), privateFuncThisTimeValue, DontEnum | DontDelete | ReadOnly),
611
        GlobalPropertyInfo(vm.propertyNames->builtinNames().thisTimeValuePrivateName(), privateFuncThisTimeValue, DontEnum | DontDelete | ReadOnly),
612
        GlobalPropertyInfo(vm.propertyNames->builtinNames().asyncFunctionResumePrivateName(), JSFunction::createBuiltinFunction(vm, asyncFunctionPrototypeAsyncFunctionResumeCodeGenerator(vm), this), DontEnum | DontDelete | ReadOnly),
603
#if ENABLE(INTL)
613
#if ENABLE(INTL)
604
        GlobalPropertyInfo(vm.propertyNames->builtinNames().CollatorPrivateName(), intl->getDirect(vm, vm.propertyNames->Collator), DontEnum | DontDelete | ReadOnly),
614
        GlobalPropertyInfo(vm.propertyNames->builtinNames().CollatorPrivateName(), intl->getDirect(vm, vm.propertyNames->Collator), DontEnum | DontDelete | ReadOnly),
605
        GlobalPropertyInfo(vm.propertyNames->builtinNames().DateTimeFormatPrivateName(), intl->getDirect(vm, vm.propertyNames->DateTimeFormat), DontEnum | DontDelete | ReadOnly),
615
        GlobalPropertyInfo(vm.propertyNames->builtinNames().DateTimeFormatPrivateName(), intl->getDirect(vm, vm.propertyNames->DateTimeFormat), DontEnum | DontDelete | ReadOnly),
- a/Source/JavaScriptCore/runtime/JSGlobalObject.h +5 lines
Lines 54-59 class JSGlobalObjectInspectorController; a/Source/JavaScriptCore/runtime/JSGlobalObject.h_sec1
54
namespace JSC {
54
namespace JSC {
55
55
56
class ArrayPrototype;
56
class ArrayPrototype;
57
class AsyncFunctionPrototype;
57
class BooleanPrototype;
58
class BooleanPrototype;
58
class ConsoleClient;
59
class ConsoleClient;
59
class Debugger;
60
class Debugger;
Lines 234-239 protected: a/Source/JavaScriptCore/runtime/JSGlobalObject.h_sec2
234
    WriteBarrier<ObjectPrototype> m_objectPrototype;
235
    WriteBarrier<ObjectPrototype> m_objectPrototype;
235
    WriteBarrier<FunctionPrototype> m_functionPrototype;
236
    WriteBarrier<FunctionPrototype> m_functionPrototype;
236
    WriteBarrier<ArrayPrototype> m_arrayPrototype;
237
    WriteBarrier<ArrayPrototype> m_arrayPrototype;
238
    WriteBarrier<AsyncFunctionPrototype> m_asyncFunctionPrototype;
237
    WriteBarrier<RegExpPrototype> m_regExpPrototype;
239
    WriteBarrier<RegExpPrototype> m_regExpPrototype;
238
    WriteBarrier<IteratorPrototype> m_iteratorPrototype;
240
    WriteBarrier<IteratorPrototype> m_iteratorPrototype;
239
    WriteBarrier<GeneratorFunctionPrototype> m_generatorFunctionPrototype;
241
    WriteBarrier<GeneratorFunctionPrototype> m_generatorFunctionPrototype;
Lines 272-277 protected: a/Source/JavaScriptCore/runtime/JSGlobalObject.h_sec3
272
    PropertyOffset m_functionNameOffset;
274
    PropertyOffset m_functionNameOffset;
273
    WriteBarrier<Structure> m_privateNameStructure;
275
    WriteBarrier<Structure> m_privateNameStructure;
274
    WriteBarrier<Structure> m_regExpStructure;
276
    WriteBarrier<Structure> m_regExpStructure;
277
    WriteBarrier<Structure> m_asyncFunctionStructure;
275
    WriteBarrier<Structure> m_generatorFunctionStructure;
278
    WriteBarrier<Structure> m_generatorFunctionStructure;
276
    WriteBarrier<Structure> m_consoleStructure;
279
    WriteBarrier<Structure> m_consoleStructure;
277
    WriteBarrier<Structure> m_dollarVMStructure;
280
    WriteBarrier<Structure> m_dollarVMStructure;
Lines 462-467 public: a/Source/JavaScriptCore/runtime/JSGlobalObject.h_sec4
462
    ObjectPrototype* objectPrototype() const { return m_objectPrototype.get(); }
465
    ObjectPrototype* objectPrototype() const { return m_objectPrototype.get(); }
463
    FunctionPrototype* functionPrototype() const { return m_functionPrototype.get(); }
466
    FunctionPrototype* functionPrototype() const { return m_functionPrototype.get(); }
464
    ArrayPrototype* arrayPrototype() const { return m_arrayPrototype.get(); }
467
    ArrayPrototype* arrayPrototype() const { return m_arrayPrototype.get(); }
468
    AsyncFunctionPrototype* asyncFunctionPrototype() const { return m_asyncFunctionPrototype.get(); }
465
    BooleanPrototype* booleanPrototype() const { return m_booleanPrototype.get(); }
469
    BooleanPrototype* booleanPrototype() const { return m_booleanPrototype.get(); }
466
    StringPrototype* stringPrototype() const { return m_stringPrototype.get(); }
470
    StringPrototype* stringPrototype() const { return m_stringPrototype.get(); }
467
    SymbolPrototype* symbolPrototype() const { return m_symbolPrototype.get(); }
471
    SymbolPrototype* symbolPrototype() const { return m_symbolPrototype.get(); }
Lines 529-534 public: a/Source/JavaScriptCore/runtime/JSGlobalObject.h_sec5
529
    Structure* internalFunctionStructure() const { return m_internalFunctionStructure.get(); }
533
    Structure* internalFunctionStructure() const { return m_internalFunctionStructure.get(); }
530
    Structure* mapStructure() const { return m_mapStructure.get(); }
534
    Structure* mapStructure() const { return m_mapStructure.get(); }
531
    Structure* regExpStructure() const { return m_regExpStructure.get(); }
535
    Structure* regExpStructure() const { return m_regExpStructure.get(); }
536
    Structure* asyncFunctionStructure() const { return m_asyncFunctionStructure.get(); }
532
    Structure* generatorFunctionStructure() const { return m_generatorFunctionStructure.get(); }
537
    Structure* generatorFunctionStructure() const { return m_generatorFunctionStructure.get(); }
533
    Structure* setStructure() const { return m_setStructure.get(); }
538
    Structure* setStructure() const { return m_setStructure.get(); }
534
    Structure* stringObjectStructure() const { return m_stringObjectStructure.get(); }
539
    Structure* stringObjectStructure() const { return m_stringObjectStructure.get(); }
- a/Source/JavaScriptCore/tests/es6.yaml +14 lines
Lines 1236-1238 a/Source/JavaScriptCore/tests/es6.yaml_sec1
1236
  cmd: runES6 :normal
1236
  cmd: runES6 :normal
1237
- path: es6/Object_static_methods_Object.getOwnPropertyDescriptors-proxy.js
1237
- path: es6/Object_static_methods_Object.getOwnPropertyDescriptors-proxy.js
1238
  cmd: runES6 :fail
1238
  cmd: runES6 :fail
1239
- path: es6/async-await-reserved-word.js
1240
  cmd: runES6 :normal
1241
- path: es6/async-await-basic.js
1242
  cmd: runES6 :normal
1243
- path: es6/async_arrow_functions_lexical_arguments_binding.js
1244
  cmd: runES6 :normal
1245
- path: es6/async_arrow_functions_lexical_new.target_binding.js
1246
  cmd: runES6 :normal
1247
- path: es6/async_arrow_functions_lexical_super_binding.js
1248
  cmd: runES6 :normal
1249
- path: es6/async_arrow_functions_lexical_this_binding.js
1250
  cmd: runES6 :normal
1251
- path: es6/async-await-mozilla.js
1252
  cmd: runES6 :normal
- a/Source/JavaScriptCore/tests/es6/async-await-basic.js +220 lines
Line 0 a/Source/JavaScriptCore/tests/es6/async-await-basic.js_sec1
1
function shouldBe(expected, actual, msg) {
2
    if (msg === void 0)
3
        msg = "";
4
    else
5
        msg = " for " + msg;
6
    if (actual !== expected)
7
        throw new Error("bad value" + msg + ": " + actual + ". Expected " + expected);
8
}
9
10
function shouldBeAsync(expected, run, msg) {
11
    let actual;
12
    var hadError = false;
13
    run().then(function(value) { actual = value; },
14
               function(error) { hadError = true; actual = error; });
15
    drainMicrotasks();
16
17
    if (hadError)
18
        throw actual;
19
20
    shouldBe(expected, actual, msg);
21
}
22
23
function shouldThrow(run, errorType, message) {
24
    let actual;
25
    var hadError = false;
26
27
    try {
28
        actual = run();
29
    } catch (e) {
30
        hadError = true;
31
        actual = e;
32
    }
33
34
    if (!hadError)
35
        throw new Error("Expected " + run + "() to throw " + errorType.name + ", but did not throw.");
36
    if (!(actual instanceof errorType))
37
        throw new Error("Expeced " + run + "() to throw " + errorType.name + " , but threw '" + actual + "'");
38
    if (message !== void 0 && actual.message !== message)
39
        throw new Error("Expected " + run + "() to throw '" + message + "', but threw '" + actual.message + "'");
40
}
41
42
function shouldThrowAsync(run, errorType, message) {
43
    let actual;
44
    var hadError = false;
45
    run().then(function(value) { actual = value; },
46
               function(error) { hadError = true; actual = error; });
47
    drainMicrotasks();
48
49
    if (!hadError)
50
        throw new Error("Expected " + run + "() to throw " + errorType.name + ", but did not throw.");
51
    if (!(actual instanceof errorType))
52
        throw new Error("Expected " + run + "() to throw " + errorType.name + ", but threw '" + actual + "'");
53
    if (message !== void 0 && actual.message !== message)
54
        throw new Error("Expected " + run + "() to throw '" + message + "', but threw '" + actual.message + "'");
55
}
56
57
// Let functionPrototype be the intrinsic object %AsyncFunctionPrototype%.
58
async function asyncFunctionForProto() {}
59
shouldBe(AsyncFunction.prototype, Object.getPrototypeOf(asyncFunctionForProto));
60
shouldBe(AsyncFunction.prototype, Object.getPrototypeOf(async function() {}));
61
shouldBe(AsyncFunction.prototype, Object.getPrototypeOf(async () => {}));
62
shouldBe(AsyncFunction.prototype, Object.getPrototypeOf({ async method() {} }.method));
63
64
// FIXME: AsyncFunction constructor should build functions with correct prototype.
65
//shouldBe(AsyncFunction.prototype, Object.getPrototypeOf(AsyncFunction()));
66
67
// Let F be ! FunctionAllocate(functionPrototype, Strict, "non-constructor")
68
async function asyncNonConstructorDecl() {}
69
shouldThrow(() => new asyncNonConstructorDecl(), TypeError);
70
shouldThrow(() => new (async function() {}), TypeError);
71
shouldThrow(() => new ({ async nonConstructor() {} }).nonConstructor(), TypeError);
72
shouldThrow(() => new (() => "not a constructor!"), TypeError);
73
shouldThrow(() => new (AsyncFunction()), TypeError);
74
75
// Normal completion
76
async function asyncDecl() { return "test"; }
77
shouldBeAsync("test", asyncDecl);
78
shouldBeAsync("test2", async function() { return "test2"; });
79
shouldBeAsync("test3", async () => "test3");
80
shouldBeAsync("test4", () => ({ async f() { return "test4"; } }).f());
81
82
class MyError extends Error {};
83
84
// Throw completion
85
async function asyncDeclThrower(e) { throw new MyError(e); }
86
shouldThrowAsync(() => asyncDeclThrower("boom!"), MyError, "boom!");
87
shouldThrowAsync(() => (async function(e) { throw new MyError(e); })("boom!!!"), MyError, "boom!!!");
88
shouldThrowAsync(() => (async e => { throw new MyError(e) })("boom!!"), MyError, "boom!!");
89
shouldThrowAsync(() => ({ async thrower(e) { throw new MyError(e); } }).thrower("boom!!!!"), MyError, "boom!!!!");
90
91
function resolveLater(value) { return Promise.resolve(value); }
92
function rejectLater(error) { return Promise.reject(error); }
93
94
// Resume after Normal completion
95
var log = [];
96
async function resumeAfterNormal(value) {
97
    log.push("start:" + value);
98
    value = await resolveLater(value + 1);
99
    log.push("resume:" + value);
100
    value = await resolveLater(value + 1);
101
    log.push("resume:" + value);
102
    return value + 1;
103
}
104
105
shouldBeAsync(4, () => resumeAfterNormal(1));
106
shouldBe("start:1 resume:2 resume:3", log.join(" "));
107
108
var O = {
109
    async resumeAfterNormal(value) {
110
        log.push("start:" + value);
111
        value = await resolveLater(value + 1);
112
        log.push("resume:" + value);
113
        value = await resolveLater(value + 1);
114
        log.push("resume:" + value);
115
        return value + 1;
116
    }
117
};
118
log = [];
119
shouldBeAsync(5, () => O.resumeAfterNormal(2));
120
shouldBe("start:2 resume:3 resume:4", log.join(" "));
121
122
var resumeAfterNormalArrow = async (value) => {
123
    log.push("start:" + value);
124
    value = await resolveLater(value + 1);
125
    log.push("resume:" + value);
126
    value = await resolveLater(value + 1);
127
    log.push("resume:" + value);
128
    return value + 1;
129
};
130
log = [];
131
shouldBeAsync(6, () => resumeAfterNormalArrow(3));
132
shouldBe("start:3 resume:4 resume:5", log.join(" "));
133
134
var resumeAfterNormalEval = AsyncFunction("value", `
135
    log.push("start:" + value);
136
    value = await resolveLater(value + 1);
137
    log.push("resume:" + value);
138
    value = await resolveLater(value + 1);
139
    log.push("resume:" + value);
140
    return value + 1;
141
`);
142
log = [];
143
shouldBeAsync(7, () => resumeAfterNormalEval(4));
144
shouldBe("start:4 resume:5 resume:6", log.join(" "));
145
146
// Resume after Throw completion
147
async function resumeAfterThrow(value) {
148
    log.push("start:" + value);
149
    try {
150
        value = await rejectLater("throw1");
151
    } catch (e) {
152
        log.push("resume:" + e);
153
    }
154
    try {
155
        value = await rejectLater("throw2");
156
    } catch (e) {
157
        log.push("resume:" + e);
158
    }
159
    return value + 1;
160
}
161
162
log = [];
163
shouldBeAsync(2, () => resumeAfterThrow(1));
164
shouldBe("start:1 resume:throw1 resume:throw2", log.join(" "));
165
166
var O = {
167
    async resumeAfterThrow(value) {
168
        log.push("start:" + value);
169
        try {
170
            value = await rejectLater("throw1");
171
        } catch (e) {
172
            log.push("resume:" + e);
173
        }
174
        try {
175
            value = await rejectLater("throw2");
176
        } catch (e) {
177
            log.push("resume:" + e);
178
        }
179
        return value + 1;
180
    }
181
}
182
log = [];
183
shouldBeAsync(3, () => O.resumeAfterThrow(2));
184
shouldBe("start:2 resume:throw1 resume:throw2", log.join(" "));
185
186
var resumeAfterThrowArrow = async (value) => {
187
    log.push("start:" + value);
188
    try {
189
        value = await rejectLater("throw1");
190
    } catch (e) {
191
        log.push("resume:" + e);
192
    }
193
    try {
194
        value = await rejectLater("throw2");
195
    } catch (e) {
196
        log.push("resume:" + e);
197
    }
198
    return value + 1;
199
};
200
log = [];
201
shouldBeAsync(4, () => resumeAfterThrowArrow(3));
202
shouldBe("start:3 resume:throw1 resume:throw2", log.join(" "));
203
204
var resumeAfterThrowEval = AsyncFunction("value", `
205
    log.push("start:" + value);
206
    try {
207
        value = await rejectLater("throw1");
208
    } catch (e) {
209
        log.push("resume:" + e);
210
    }
211
    try {
212
        value = await rejectLater("throw2");
213
    } catch (e) {
214
        log.push("resume:" + e);
215
    }
216
    return value + 1;
217
`);
218
log = [];
219
shouldBeAsync(5, () => resumeAfterThrowEval(4));
220
shouldBe("start:4 resume:throw1 resume:throw2", log.join(" "));
- a/Source/JavaScriptCore/tests/es6/async-await-mozilla.js +304 lines
Line 0 a/Source/JavaScriptCore/tests/es6/async-await-mozilla.js_sec1
1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
 * License, v. 2.0. If a copy of the MPL was not distributed with this
3
 * file, You can obtain one at http://moz.org/MPL/2.0/. */
4
5
function shouldBe(expected, actual, msg) {
6
    if (msg === void 0)
7
        msg = "";
8
    else
9
        msg = " for " + msg;
10
    if (actual !== expected)
11
        throw new Error("bad value" + msg + ": " + actual + ". Expected " + expected);
12
}
13
14
function shouldBeAsync(expected, run, msg) {
15
    let actual;
16
    var hadError = false;
17
    run().then(function(value) { actual = value; },
18
               function(error) { hadError = true; actual = error; });
19
    drainMicrotasks();
20
    if (hadError)
21
        throw actual;
22
    shouldBe(expected, actual, msg);
23
}
24
25
function shouldThrow(run, errorType, message) {
26
    let actual;
27
    var hadError = false;
28
    try {
29
        actual = run();
30
    } catch (e) {
31
        hadError = true;
32
        actual = e;
33
    }
34
    if (!hadError)
35
        throw new Error("Expected " + run + "() to throw " + errorType.name + ", but did not throw.");
36
    if (!(actual instanceof errorType))
37
        throw new Error("Expeced " + run + "() to throw " + errorType.name + " , but threw '" + actual + "'");
38
    if (message !== void 0 && actual.message !== message)
39
        throw new Error("Expected " + run + "() to throw '" + message + "', but threw '" + actual.message + "'");
40
}
41
42
function shouldThrowAsync(run, errorType, message) {
43
    let actual;
44
    var hadError = false;
45
    run().then(function(value) { actual = value; },
46
               function(error) { hadError = true; actual = error; });
47
    drainMicrotasks();
48
    if (!hadError)
49
        throw new Error("Expected " + run + "() to throw " + errorType.name + ", but did not throw.");
50
    if (!(actual instanceof errorType))
51
        throw new Error("Expected " + run + "() to throw " + errorType.name + ", but threw '" + actual + "'");
52
    if (message !== void 0 && actual.message !== message)
53
        throw new Error("Expected " + run + "() to throw '" + message + "', but threw '" + actual.message + "'");
54
}
55
56
function assert(cond, msg = "") {
57
    if (!cond)
58
        throw new Error(msg);
59
}
60
61
function shouldThrowSyntaxError(str, message) {
62
    var hadError = false;
63
    try {
64
        eval(str);
65
    } catch (e) {
66
        if (e instanceof SyntaxError) {
67
            hadError = true;
68
            if (typeof message === "string")
69
                assert(e.message === message, "Expected '" + message + "' but threw '" + e.message + "'");
70
        }
71
    }
72
    assert(hadError, "Did not throw syntax error");
73
}
74
75
// semantics.js
76
(function mozSemantics() {
77
78
async function empty() {
79
}
80
81
async function simpleReturn() {
82
    return 1;
83
}
84
85
async function simpleAwait() {
86
    var result = await 2;
87
    return result;
88
}
89
90
async function simpleAwaitAsync() {
91
    var result = await simpleReturn();
92
    return 2 + result;
93
}
94
95
async function returnOtherAsync() {
96
    return 1 + await simpleAwaitAsync();
97
}
98
99
async function simpleThrower() {
100
    throw new Error();
101
}
102
103
async function delegatedThrower() {
104
    var val = await simpleThrower();
105
    return val;
106
}
107
108
async function tryCatch() {
109
    try {
110
        await delegatedThrower();
111
        return 'FAILED';
112
    } catch (_) {
113
        return 5;
114
    }
115
}
116
117
async function tryCatchThrow() {
118
    try {
119
        await delegatedThrower();
120
        return 'FAILED';
121
    } catch (_) {
122
        return delegatedThrower();
123
    }
124
}
125
126
async function wellFinally() {
127
    try {
128
        await delegatedThrower();
129
    } catch (_) {
130
        return 'FAILED';
131
    } finally {
132
        return 6;
133
    }
134
}
135
136
async function finallyMayFail() {
137
    try {
138
        await delegatedThrower();
139
    } catch (_) {
140
        return 5;
141
    } finally {
142
        return delegatedThrower();
143
    }
144
}
145
146
async function embedded() {
147
    async function inner() {
148
        return 7;
149
    }
150
    return await inner();
151
}
152
153
// recursion, it works!
154
async function fib(n) {
155
    return (n == 0 || n == 1) ? n : await fib(n - 1) + await fib(n - 2);
156
}
157
158
// mutual recursion
159
async function isOdd(n) {
160
    async function isEven(n) {
161
        return n === 0 || await isOdd(n - 1);
162
    }
163
    return n !== 0 && await isEven(n - 1);
164
}
165
166
// recursion, take three!
167
var hardcoreFib = async function fib2(n) {
168
    return (n == 0 || n == 1) ? n : await fib2(n - 1) + await fib2(n - 2);
169
}
170
171
var asyncExpr = async function() {
172
    return 10;
173
}
174
175
var namedAsyncExpr = async function simple() {
176
    return 11;
177
}
178
179
async function executionOrder() {
180
    var value = 0;
181
    async function first() {
182
        return (value = value === 0 ? 1 : value);
183
    }
184
    async function second() {
185
        return (value = value === 0 ? 2 : value);
186
    }
187
    async function third() {
188
        return (value = value === 0 ? 3 : value);
189
    }
190
    return await first() + await second() + await third() + 6;
191
}
192
193
async function miscellaneous() {
194
    if (arguments.length === 3 &&
195
        arguments.callee.name === "miscellaneous")
196
        return 14;
197
}
198
199
function thrower() {
200
    throw 15;
201
}
202
203
async function defaultArgs(arg = thrower()) {
204
}
205
206
// Async functions are not constructible
207
shouldThrow(() => {
208
    async function Person() {
209
    }
210
    new Person();
211
}, TypeError);
212
213
shouldBeAsync(undefined, empty);
214
shouldBeAsync(1, simpleReturn);
215
shouldBeAsync(2, simpleAwait);
216
shouldBeAsync(3, simpleAwaitAsync);
217
shouldBeAsync(4, returnOtherAsync);
218
shouldThrowAsync(simpleThrower, Error);
219
shouldBeAsync(5, tryCatch);
220
shouldBeAsync(6, wellFinally);
221
shouldThrowAsync(finallyMayFail, Error);
222
shouldBeAsync(7, embedded);
223
shouldBeAsync(8, () => fib(6));
224
shouldBeAsync(9, executionOrder);
225
shouldBeAsync(10, asyncExpr);
226
shouldBeAsync(11, namedAsyncExpr);
227
shouldBeAsync(12, () => isOdd(12).then(v => v ? "oops" : 12));
228
shouldBeAsync(13, () => hardcoreFib(7));
229
shouldBeAsync(14, () => miscellaneous(1, 2, 3));
230
shouldBeAsync(15, () => defaultArgs().catch(e => e));
231
232
})();
233
234
// methods.js
235
(function mozMethods() {
236
237
class X {
238
    constructor() {
239
        this.value = 42;
240
    }
241
    async getValue() {
242
        return this.value;
243
    }
244
    setValue(value) {
245
        this.value = value;
246
    }
247
    async increment() {
248
        var value = await this.getValue();
249
        this.setValue(value + 1);
250
        return this.getValue();
251
    }
252
    async getBaseClassName() {
253
        return 'X';
254
    }
255
    static async getStaticValue() {
256
        return 44;
257
    }
258
}
259
260
class Y extends X {
261
    async getBaseClassName() {
262
        return super.getBaseClassName();
263
    }
264
}
265
266
var objLiteral = {
267
    async get() {
268
        return 45;
269
    },
270
    someStuff: 5
271
};
272
273
var x = new X();
274
var y = new Y();
275
276
shouldBeAsync(42, () => x.getValue());
277
shouldBeAsync(43, () => x.increment());
278
shouldBeAsync(44, () => X.getStaticValue());
279
shouldBeAsync(45, () => objLiteral.get());
280
shouldBeAsync('X', () => y.getBaseClassName());
281
282
})();
283
284
(function mozFunctionNameInferrence() {
285
286
async function test() { }
287
288
var anon = async function() { }
289
290
shouldBe("test", test.name);
291
shouldBe("anon", anon.name);
292
293
})();
294
295
(function mozSyntaxErrors() {
296
297
shouldThrowSyntaxError("'use strict'; async function eval() {}");
298
shouldThrowSyntaxError("'use strict'; async function arguments() {}");
299
shouldThrowSyntaxError("async function a(k = super.prop) { }");
300
shouldThrowSyntaxError("async function a() { super.prop(); }");
301
shouldThrowSyntaxError("async function a() { super(); }");
302
shouldThrowSyntaxError("async function a(k = await 3) {}");
303
304
})();
- a/Source/JavaScriptCore/tests/es6/async-await-reserved-word.js +161 lines
Line 0 a/Source/JavaScriptCore/tests/es6/async-await-reserved-word.js_sec1
1
function assert(cond, msg = "") {
2
    if (!cond)
3
        throw new Error(msg);
4
}
5
noInline(assert);
6
7
function shouldThrowSyntaxError(str, message) {
8
    var hadError = false;
9
    try {
10
        eval(str);
11
    } catch (e) {
12
        if (e instanceof SyntaxError) {
13
            hadError = true;
14
            if (typeof message === "string")
15
                assert(e.message === message, "Expected '" + message + "' but threw '" + e.message + "'");
16
        }
17
    }
18
    assert(hadError, "Did not throw syntax error");
19
}
20
noInline(shouldThrowSyntaxError);
21
22
// AsyncFunctionExpression
23
shouldThrowSyntaxError("(async function() { var await; })", "Can't use 'await' as a variable name in an async function.");
24
shouldThrowSyntaxError("(async function() { var [await] = []; })", "Can't use 'await' as a variable name in an async function.");
25
shouldThrowSyntaxError("(async function() { var [...await] = []; })", "Can't use 'await' as a variable name in an async function.");
26
shouldThrowSyntaxError("(async function() { var {await} = {}; })", "Can't use 'await' as a variable name in an async function.");
27
shouldThrowSyntaxError("(async function() { var {isAsync: await} = {}; })", "Can't use 'await' as a variable name in an async function.");
28
shouldThrowSyntaxError("(async function() { var {isAsync: await} = {}; })", "Can't use 'await' as a variable name in an async function.");
29
shouldThrowSyntaxError("(async function() { let await; })", "Can't use 'await' as a lexical variable name in an async function.");
30
shouldThrowSyntaxError("(async function() { let [await] = []; })", "Can't use 'await' as a lexical variable name in an async function.");
31
shouldThrowSyntaxError("(async function() { let [...await] = []; })", "Can't use 'await' as a lexical variable name in an async function.");
32
shouldThrowSyntaxError("(async function() { let {await} = {}; })", "Can't use 'await' as a lexical variable name in an async function.");
33
shouldThrowSyntaxError("(async function() { let {isAsync: await} = {}; })", "Can't use 'await' as a lexical variable name in an async function.");
34
shouldThrowSyntaxError("(async function() { let {isAsync: await} = {}; })", "Can't use 'await' as a lexical variable name in an async function.");
35
shouldThrowSyntaxError("(async function() { const await; })", "Can't use 'await' as a lexical variable name in an async function.");
36
shouldThrowSyntaxError("(async function() { const [await] = []; })", "Can't use 'await' as a lexical variable name in an async function.");
37
shouldThrowSyntaxError("(async function() { const [...await] = []; })", "Can't use 'await' as a lexical variable name in an async function.");
38
shouldThrowSyntaxError("(async function() { const {await} = {}; })", "Can't use 'await' as a lexical variable name in an async function.");
39
shouldThrowSyntaxError("(async function() { const {isAsync: await} = {}; })", "Can't use 'await' as a lexical variable name in an async function.");
40
shouldThrowSyntaxError("(async function() { const {isAsync: await} = {}; })", "Can't use 'await' as a lexical variable name in an async function.");
41
shouldThrowSyntaxError("(async function() { function await() {} })", "Cannot declare function named 'await' in an async function.");
42
shouldThrowSyntaxError("(async function() { async function await() {} })", "Cannot declare function named 'await' in an async function.");
43
shouldThrowSyntaxError("(async function(await) {})", "Can't use 'await' as a parameter name in an async function.");
44
shouldThrowSyntaxError("(async function f([await]) {})", "Can't use 'await' as a parameter name in an async function.");
45
shouldThrowSyntaxError("(async function f([...await]) {})", "Can't use 'await' as a parameter name in an async function.");
46
shouldThrowSyntaxError("(async function f(...await) {})", "Can't use 'await' as a parameter name in an async function.");
47
shouldThrowSyntaxError("(async function f({await}) {})", "Can't use 'await' as a parameter name in an async function.");
48
shouldThrowSyntaxError("(async function f({isAsync: await}) {})", "Can't use 'await' as a parameter name in an async function.");
49
50
// AsyncFunctionDeclaration
51
shouldThrowSyntaxError("async function f() { var await; }", "Can't use 'await' as a variable name in an async function.");
52
shouldThrowSyntaxError("async function f() { var [await] = []; })", "Can't use 'await' as a variable name in an async function.");
53
shouldThrowSyntaxError("async function f() { var [...await] = []; })", "Can't use 'await' as a variable name in an async function.");
54
shouldThrowSyntaxError("async function f() { var {await} = {}; })", "Can't use 'await' as a variable name in an async function.");
55
shouldThrowSyntaxError("async function f() { var {isAsync: await} = {}; })", "Can't use 'await' as a variable name in an async function.");
56
shouldThrowSyntaxError("async function f() { var {isAsync: await} = {}; })", "Can't use 'await' as a variable name in an async function.");
57
shouldThrowSyntaxError("async function f() { let await; }", "Can't use 'await' as a lexical variable name in an async function.");
58
shouldThrowSyntaxError("async function f() { let [await] = []; }", "Can't use 'await' as a lexical variable name in an async function.");
59
shouldThrowSyntaxError("async function f() { let [...await] = []; }", "Can't use 'await' as a lexical variable name in an async function.");
60
shouldThrowSyntaxError("async function f() { let {await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
61
shouldThrowSyntaxError("async function f() { let {isAsync: await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
62
shouldThrowSyntaxError("async function f() { let {isAsync: await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
63
shouldThrowSyntaxError("async function f() { const await; }", "Can't use 'await' as a lexical variable name in an async function.");
64
shouldThrowSyntaxError("async function f() { const [await] = []; }", "Can't use 'await' as a lexical variable name in an async function.");
65
shouldThrowSyntaxError("async function f() { const [...await] = []; }", "Can't use 'await' as a lexical variable name in an async function.");
66
shouldThrowSyntaxError("async function f() { const {await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
67
shouldThrowSyntaxError("async function f() { const {isAsync: await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
68
shouldThrowSyntaxError("async function f() { const {isAsync: await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
69
shouldThrowSyntaxError("async function f() { function await() {} }", "Cannot declare function named 'await' in an async function.");
70
shouldThrowSyntaxError("async function f() { async function await() {} }", "Cannot declare function named 'await' in an async function.");
71
shouldThrowSyntaxError("async function f(await) {}", "Can't use 'await' as a parameter name in an async function.");
72
shouldThrowSyntaxError("async function f([await]) {}", "Can't use 'await' as a parameter name in an async function.");
73
shouldThrowSyntaxError("async function f([...await]) {}", "Can't use 'await' as a parameter name in an async function.");
74
shouldThrowSyntaxError("async function f(...await) {}", "Can't use 'await' as a parameter name in an async function.");
75
shouldThrowSyntaxError("async function f({await}) {}", "Can't use 'await' as a parameter name in an async function.");
76
shouldThrowSyntaxError("async function f({isAsync: await}) {}", "Can't use 'await' as a parameter name in an async function.");
77
78
// AsyncArrowFunction
79
shouldThrowSyntaxError("var f = async () => { var await; }", "Can't use 'await' as a variable name in an async function.");
80
shouldThrowSyntaxError("var f = async () => { var [await] = []; })", "Can't use 'await' as a variable name in an async function.");
81
shouldThrowSyntaxError("var f = async () => { var [...await] = []; })", "Can't use 'await' as a variable name in an async function.");
82
shouldThrowSyntaxError("var f = async () => { var {await} = {}; })", "Can't use 'await' as a variable name in an async function.");
83
shouldThrowSyntaxError("var f = async () => { var {isAsync: await} = {}; })", "Can't use 'await' as a variable name in an async function.");
84
shouldThrowSyntaxError("var f = async () => { var {isAsync: await} = {}; })", "Can't use 'await' as a variable name in an async function.");
85
shouldThrowSyntaxError("var f = async () => { let await; }", "Can't use 'await' as a lexical variable name in an async function.");
86
shouldThrowSyntaxError("var f = async () => { let [await] = []; }", "Can't use 'await' as a lexical variable name in an async function.");
87
shouldThrowSyntaxError("var f = async () => { let [...await] = []; }", "Can't use 'await' as a lexical variable name in an async function.");
88
shouldThrowSyntaxError("var f = async () => { let {await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
89
shouldThrowSyntaxError("var f = async () => { let {isAsync: await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
90
shouldThrowSyntaxError("var f = async () => { let {isAsync: await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
91
shouldThrowSyntaxError("var f = async () => { const await; }", "Can't use 'await' as a lexical variable name in an async function.");
92
shouldThrowSyntaxError("var f = async () => { const [await] = []; }", "Can't use 'await' as a lexical variable name in an async function.");
93
shouldThrowSyntaxError("var f = async () => { const [...await] = []; }", "Can't use 'await' as a lexical variable name in an async function.");
94
shouldThrowSyntaxError("var f = async () => { const {await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
95
shouldThrowSyntaxError("var f = async () => { const {isAsync: await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
96
shouldThrowSyntaxError("var f = async () => { const {isAsync: await} = {}; }", "Can't use 'await' as a lexical variable name in an async function.");
97
shouldThrowSyntaxError("var f = async () => { function await() {} }", "Cannot declare function named 'await' in an async function.");
98
shouldThrowSyntaxError("var f = async () => { async function await() {} }", "Cannot declare function named 'await' in an async function.");
99
shouldThrowSyntaxError("var f = async (await) => {}", "Can't use 'await' as a parameter name in an async function.");
100
shouldThrowSyntaxError("var f = async ([await]) => {}", "Can't use 'await' as a parameter name in an async function.");
101
shouldThrowSyntaxError("var f = async ([...await]) => {}", "Can't use 'await' as a parameter name in an async function.");
102
shouldThrowSyntaxError("var f = async (...await) => {}", "Can't use 'await' as a parameter name in an async function.");
103
shouldThrowSyntaxError("var f = async ({await}) => {}", "Can't use 'await' as a parameter name in an async function.");
104
shouldThrowSyntaxError("var f = async ({isAsync: await}) => {}", "Can't use 'await' as a parameter name in an async function.");
105
shouldThrowSyntaxError("var f = async await => {}", "Can't use 'await' as a parameter name in an async function.");
106
107
// AsyncMethod
108
shouldThrowSyntaxError("var O = { async f() { var await; } }", "Can't use 'await' as a variable name in an async function.");
109
shouldThrowSyntaxError("var O = { async f() { var [await] = []; } }", "Can't use 'await' as a variable name in an async function.");
110
shouldThrowSyntaxError("var O = { async f() { var [...await] = []; } }", "Can't use 'await' as a variable name in an async function.");
111
shouldThrowSyntaxError("var O = { async f() { var {await} = {}; } }", "Can't use 'await' as a variable name in an async function.");
112
shouldThrowSyntaxError("var O = { async f() { var {isAsync: await} = {}; } }", "Can't use 'await' as a variable name in an async function.");
113
shouldThrowSyntaxError("var O = { async f() { var {isAsync: await} = {}; } }", "Can't use 'await' as a variable name in an async function.");
114
shouldThrowSyntaxError("var O = { async f() { let await; } }", "Can't use 'await' as a lexical variable name in an async function.");
115
shouldThrowSyntaxError("var O = { async f() { let [await] = []; } }", "Can't use 'await' as a lexical variable name in an async function.");
116
shouldThrowSyntaxError("var O = { async f() { let [...await] = []; } }", "Can't use 'await' as a lexical variable name in an async function.");
117
shouldThrowSyntaxError("var O = { async f() { let {await} = {}; } }", "Can't use 'await' as a lexical variable name in an async function.");
118
shouldThrowSyntaxError("var O = { async f() { let {isAsync: await} = {}; } }", "Can't use 'await' as a lexical variable name in an async function.");
119
shouldThrowSyntaxError("var O = { async f() { let {isAsync: await} = {}; } }", "Can't use 'await' as a lexical variable name in an async function.");
120
shouldThrowSyntaxError("var O = { async f() { const await; } }", "Can't use 'await' as a lexical variable name in an async function.");
121
shouldThrowSyntaxError("var O = { async f() { const [await] = []; } }", "Can't use 'await' as a lexical variable name in an async function.");
122
shouldThrowSyntaxError("var O = { async f() { const [...await] = []; } }", "Can't use 'await' as a lexical variable name in an async function.");
123
shouldThrowSyntaxError("var O = { async f() { const {await} = {}; } }", "Can't use 'await' as a lexical variable name in an async function.");
124
shouldThrowSyntaxError("var O = { async f() { const {isAsync: await} = {}; } }", "Can't use 'await' as a lexical variable name in an async function.");
125
shouldThrowSyntaxError("var O = { async f() { const {isAsync: await} = {}; } }", "Can't use 'await' as a lexical variable name in an async function.");
126
shouldThrowSyntaxError("var O = { async f() { function await() {} }", "Cannot declare function named 'await' in an async function.");
127
shouldThrowSyntaxError("var O = { async f() { async function await() {} } }", "Cannot declare function named 'await' in an async function.");
128
shouldThrowSyntaxError("var O = { async f(await) {} } ", "Can't use 'await' as a parameter name in an async function.");
129
shouldThrowSyntaxError("var O = { async f([await]) {}", "Can't use 'await' as a parameter name in an async function.");
130
shouldThrowSyntaxError("var O = { async f([...await]) {}", "Can't use 'await' as a parameter name in an async function.");
131
shouldThrowSyntaxError("var O = { async f(...await) {}", "Can't use 'await' as a parameter name in an async function.");
132
shouldThrowSyntaxError("var O = { async f({await}) {}", "Can't use 'await' as a parameter name in an async function.");
133
shouldThrowSyntaxError("var O = { async f({isAsync: await}) {}", "Can't use 'await' as a parameter name in an async function.");
134
135
// AsyncFunction constructor
136
shouldThrowSyntaxError("AsyncFunction('var await;')", "Can't use 'await' as a variable name in an async function.");
137
shouldThrowSyntaxError("AsyncFunction('var [await] = [];')", "Can't use 'await' as a variable name in an async function.");
138
shouldThrowSyntaxError("AsyncFunction('var [...await] = [];')", "Can't use 'await' as a variable name in an async function.");
139
shouldThrowSyntaxError("AsyncFunction('var {await} = {};')", "Can't use 'await' as a variable name in an async function.");
140
shouldThrowSyntaxError("AsyncFunction('var {isAsync: await} = {};')", "Can't use 'await' as a variable name in an async function.");
141
shouldThrowSyntaxError("AsyncFunction('var {isAsync: await} = {};')", "Can't use 'await' as a variable name in an async function.");
142
shouldThrowSyntaxError("AsyncFunction('let await;')", "Can't use 'await' as a lexical variable name in an async function.");
143
shouldThrowSyntaxError("AsyncFunction('let [await] = [];')", "Can't use 'await' as a lexical variable name in an async function.");
144
shouldThrowSyntaxError("AsyncFunction('let [...await] = [];')", "Can't use 'await' as a lexical variable name in an async function.");
145
shouldThrowSyntaxError("AsyncFunction('let {await} = {};')", "Can't use 'await' as a lexical variable name in an async function.");
146
shouldThrowSyntaxError("AsyncFunction('let {isAsync: await} = {};')", "Can't use 'await' as a lexical variable name in an async function.");
147
shouldThrowSyntaxError("AsyncFunction('let {isAsync: await} = {};')", "Can't use 'await' as a lexical variable name in an async function.");
148
shouldThrowSyntaxError("AsyncFunction('const await;')", "Can't use 'await' as a lexical variable name in an async function.");
149
shouldThrowSyntaxError("AsyncFunction('const [await] = [];')", "Can't use 'await' as a lexical variable name in an async function.");
150
shouldThrowSyntaxError("AsyncFunction('const [...await] = [];')", "Can't use 'await' as a lexical variable name in an async function.");
151
shouldThrowSyntaxError("AsyncFunction('const {await} = {};')", "Can't use 'await' as a lexical variable name in an async function.");
152
shouldThrowSyntaxError("AsyncFunction('const {isAsync: await} = {};')", "Can't use 'await' as a lexical variable name in an async function.");
153
shouldThrowSyntaxError("AsyncFunction('const {isAsync: await} = {};')", "Can't use 'await' as a lexical variable name in an async function.");
154
shouldThrowSyntaxError("AsyncFunction('function await() {}')", "Cannot declare function named 'await' in an async function.");
155
shouldThrowSyntaxError("AsyncFunction('async function await() {}')", "Cannot declare function named 'await' in an async function.");
156
shouldThrowSyntaxError("AsyncFunction('await', '')", "Can't use 'await' as a parameter name in an async function.");
157
shouldThrowSyntaxError("AsyncFunction('[await]', '')", "Can't use 'await' as a parameter name in an async function.");
158
shouldThrowSyntaxError("AsyncFunction('[...await]', '')", "Can't use 'await' as a parameter name in an async function.");
159
shouldThrowSyntaxError("AsyncFunction('...await', '')", "Can't use 'await' as a parameter name in an async function.");
160
shouldThrowSyntaxError("AsyncFunction('{await}', '')", "Can't use 'await' as a parameter name in an async function.");
161
shouldThrowSyntaxError("AsyncFunction('{isAsync: await}', '')", "Can't use 'await' as a parameter name in an async function.");
- a/Source/JavaScriptCore/tests/es6/async_arrow_functions_lexical_arguments_binding.js +44 lines
Line 0 a/Source/JavaScriptCore/tests/es6/async_arrow_functions_lexical_arguments_binding.js_sec1
1
function shouldBe(expected, actual, msg) {
2
    if (msg === void 0)
3
        msg = "";
4
    else
5
        msg = " for " + msg;
6
    if (actual !== expected)
7
        throw new Error("bad value" + msg + ": " + actual + ". Expected " + expected);
8
}
9
10
function shouldBeAsync(expected, run, msg) {
11
    let actual;
12
    var hadError = false;
13
    run().then(function(value) { actual = value; },
14
               function(error) { hadError = true; actual = error; });
15
    drainMicrotasks();
16
17
    if (hadError)
18
        throw actual;
19
20
    shouldBe(expected, actual, msg);
21
}
22
23
function shouldThrowAsync(run, errorType, message) {
24
    let actual;
25
    var hadError = false;
26
    run().then(function(value) { actual = value; },
27
               function(error) { hadError = true; actual = error; });
28
    drainMicrotasks();
29
30
    if (!hadError)
31
        throw new Error("Expected " + run + "() to throw " + errorType.name + ", but did not throw.");
32
    if (!(actual instanceof errorType))
33
        throw new Error("Expected " + run + "() to throw " + errorType.name + ", but threw '" + actual + "'");
34
    if (message !== void 0 && actual.message !== message)
35
        throw new Error("Expected " + run + "() to throw '" + message + "', but threw '" + actual.message + "'");
36
}
37
38
var noArgumentsArrow = async () => await [...arguments];
39
shouldThrowAsync(() => noArgumentsArrow(1, 2, 3), ReferenceError);
40
var noArgumentsArrow2 = async () => { return await [...arguments]; }
41
shouldThrowAsync(() => noArgumentsArrow2(1, 2, 3), ReferenceError);
42
43
shouldBeAsync("[1,2,3]", () => (function() { return (async () => JSON.stringify([...arguments]))(); })(1, 2, 3));
44
shouldBeAsync("[4,5,6]", () => (function() { return (async () => { return JSON.stringify([...await arguments]) })(); })(4, 5, 6));
- a/Source/JavaScriptCore/tests/es6/async_arrow_functions_lexical_new.target_binding.js +52 lines
Line 0 a/Source/JavaScriptCore/tests/es6/async_arrow_functions_lexical_new.target_binding.js_sec1
1
function shouldBe(expected, actual, msg) {
2
    if (msg === void 0)
3
        msg = "";
4
    else
5
        msg = " for " + msg;
6
    if (actual !== expected)
7
        throw new Error("bad value" + msg + ": " + actual + ". Expected " + expected);
8
}
9
10
function shouldBeAsync(expected, run, msg) {
11
    let actual;
12
    var hadError = false;
13
    run().then(function(value) { actual = value; },
14
               function(error) { hadError = true; actual = error; });
15
    drainMicrotasks();
16
17
    if (hadError)
18
        throw actual;
19
20
    shouldBe(expected, actual, msg);
21
}
22
23
function shouldThrowAsync(run, errorType, message) {
24
    let actual;
25
    var hadError = false;
26
    run().then(function(value) { actual = value; },
27
               function(error) { hadError = true; actual = error; });
28
    drainMicrotasks();
29
30
    if (!hadError)
31
        throw new Error("Expected " + run + "() to throw " + errorType.name + ", but did not throw.");
32
    if (!(actual instanceof errorType))
33
        throw new Error("Expected " + run + "() to throw " + errorType.name + ", but threw '" + actual + "'");
34
    if (message !== void 0 && actual.message !== message)
35
        throw new Error("Expected " + run + "() to throw '" + message + "', but threw '" + actual.message + "'");
36
}
37
38
function C1() {
39
    return async () => await new.target;
40
}
41
42
function C2() {
43
    return async () => { return await new.target };
44
}
45
46
shouldBeAsync(C1, new C1());
47
shouldBeAsync(undefined, C1());
48
shouldBeAsync(C2, new C2());
49
shouldBeAsync(undefined, C2());
50
51
shouldThrowAsync(async () => await new.target, ReferenceError);
52
shouldThrowAsync(async () => { return await new.target; }, ReferenceError);
- a/Source/JavaScriptCore/tests/es6/async_arrow_functions_lexical_super_binding.js +35 lines
Line 0 a/Source/JavaScriptCore/tests/es6/async_arrow_functions_lexical_super_binding.js_sec1
1
function shouldBe(expected, actual, msg) {
2
    if (msg === void 0)
3
        msg = "";
4
    else
5
        msg = " for " + msg;
6
    if (actual !== expected)
7
        throw new Error("bad value" + msg + ": " + actual + ". Expected " + expected);
8
}
9
10
function shouldBeAsync(expected, run, msg) {
11
    let actual;
12
    var hadError = false;
13
    run().then(function(value) { actual = value; },
14
               function(error) { hadError = true; actual = error; });
15
    drainMicrotasks();
16
17
    if (hadError)
18
        throw actual;
19
20
    shouldBe(expected, actual, msg);
21
}
22
23
class BaseClass {
24
    baseClassValue() {
25
        return "BaseClassValue";
26
    }
27
}
28
29
class ChildClass extends BaseClass {
30
    asyncSuperProp() {
31
        return async x => super.baseClassValue();
32
    }
33
}
34
35
shouldBeAsync("BaseClassValue", new ChildClass().asyncSuperProp());
- a/Source/JavaScriptCore/tests/es6/async_arrow_functions_lexical_this_binding.js +27 lines
Line 0 a/Source/JavaScriptCore/tests/es6/async_arrow_functions_lexical_this_binding.js_sec1
1
function shouldBe(expected, actual, msg) {
2
    if (msg === void 0)
3
        msg = "";
4
    else
5
        msg = " for " + msg;
6
    if (actual !== expected)
7
        throw new Error("bad value" + msg + ": " + actual + ". Expected " + expected);
8
}
9
10
function shouldBeAsync(expected, run, msg) {
11
    let actual;
12
    var hadError = false;
13
    run().then(function(value) { actual = value; },
14
               function(error) { hadError = true; actual = error; });
15
    drainMicrotasks();
16
17
    if (hadError)
18
        throw actual;
19
20
    shouldBe(expected, actual, msg);
21
}
22
23
var d = ({ x : "bar", y : function() { return async z => this.x + z; }}).y();
24
var e = { x : "baz", y : d };
25
26
shouldBeAsync("barley", () => d("ley"));
27
shouldBeAsync("barley", () => e.y("ley"));

Return to Bug 156147