All prototypes should call didBecomePrototype()
[WebKit-https.git] / Source / JavaScriptCore / runtime / FunctionConstructor.cpp
1 /*
2  *  Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
3  *  Copyright (C) 2003-2019 Apple Inc. All rights reserved.
4  *
5  *  This library is free software; you can redistribute it and/or
6  *  modify it under the terms of the GNU Lesser General Public
7  *  License as published by the Free Software Foundation; either
8  *  version 2 of the License, or (at your option) any later version.
9  *
10  *  This library is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  *  Lesser General Public License for more details.
14  *
15  *  You should have received a copy of the GNU Lesser General Public
16  *  License along with this library; if not, write to the Free Software
17  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18  *
19  */
20
21 #include "config.h"
22 #include "FunctionConstructor.h"
23
24 #include "Completion.h"
25 #include "ExceptionHelpers.h"
26 #include "FunctionPrototype.h"
27 #include "JSAsyncFunction.h"
28 #include "JSAsyncGeneratorFunction.h"
29 #include "JSFunction.h"
30 #include "JSGeneratorFunction.h"
31 #include "JSGlobalObject.h"
32 #include "JSCInlines.h"
33 #include <wtf/text/StringBuilder.h>
34
35 namespace JSC {
36
37 STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(FunctionConstructor);
38
39 const ClassInfo FunctionConstructor::s_info = { "Function", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(FunctionConstructor) };
40
41 static EncodedJSValue JSC_HOST_CALL constructWithFunctionConstructor(ExecState* exec)
42 {
43     ArgList args(exec);
44     return JSValue::encode(constructFunction(exec, jsCast<InternalFunction*>(exec->jsCallee())->globalObject(exec->vm()), args, FunctionConstructionMode::Function, exec->newTarget()));
45 }
46
47 // ECMA 15.3.1 The Function Constructor Called as a Function
48 static EncodedJSValue JSC_HOST_CALL callFunctionConstructor(ExecState* exec)
49 {
50     ArgList args(exec);
51     return JSValue::encode(constructFunction(exec, jsCast<InternalFunction*>(exec->jsCallee())->globalObject(exec->vm()), args));
52 }
53
54 FunctionConstructor::FunctionConstructor(VM& vm, Structure* structure)
55     : InternalFunction(vm, structure, callFunctionConstructor, constructWithFunctionConstructor)
56 {
57 }
58
59 void FunctionConstructor::finishCreation(VM& vm, FunctionPrototype* functionPrototype)
60 {
61     Base::finishCreation(vm, vm.propertyNames->Function.string(), NameVisibility::Visible, NameAdditionMode::WithoutStructureTransition);
62     putDirectWithoutTransition(vm, vm.propertyNames->prototype, functionPrototype, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
63     putDirectWithoutTransition(vm, vm.propertyNames->length, jsNumber(1), PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum);
64     didBecomePrototype();
65 }
66
67 // ECMA 15.3.2 The Function Constructor
68 JSObject* constructFunction(ExecState* exec, JSGlobalObject* globalObject, const ArgList& args, const Identifier& functionName, const SourceOrigin& sourceOrigin, const String& sourceURL, const TextPosition& position, FunctionConstructionMode functionConstructionMode, JSValue newTarget)
69 {
70     VM& vm = exec->vm();
71     auto scope = DECLARE_THROW_SCOPE(vm);
72
73     if (UNLIKELY(!globalObject->evalEnabled())) {
74         throwException(exec, scope, createEvalError(exec, globalObject->evalDisabledErrorMessage()));
75         return nullptr;
76     }
77     RELEASE_AND_RETURN(scope, constructFunctionSkippingEvalEnabledCheck(exec, globalObject, args, functionName, sourceOrigin, sourceURL, position, -1, functionConstructionMode, newTarget));
78 }
79
80 JSObject* constructFunctionSkippingEvalEnabledCheck(
81     ExecState* exec, JSGlobalObject* globalObject, const ArgList& args, 
82     const Identifier& functionName, const SourceOrigin& sourceOrigin, const String& sourceURL, 
83     const TextPosition& position, int overrideLineNumber, FunctionConstructionMode functionConstructionMode, JSValue newTarget)
84 {
85     VM& vm = exec->vm();
86     auto scope = DECLARE_THROW_SCOPE(vm);
87
88     const char* prefix = nullptr;
89     switch (functionConstructionMode) {
90     case FunctionConstructionMode::Function:
91         prefix = "function ";
92         break;
93     case FunctionConstructionMode::Generator:
94         prefix = "function *";
95         break;
96     case FunctionConstructionMode::Async:
97         prefix = "async function ";
98         break;
99     case FunctionConstructionMode::AsyncGenerator:
100         prefix = "async function*";
101         break;
102     }
103
104     // How we stringify functions is sometimes important for web compatibility.
105     // See https://bugs.webkit.org/show_bug.cgi?id=24350.
106     String program;
107     Optional<int> functionConstructorParametersEndPosition = WTF::nullopt;
108     if (args.isEmpty())
109         program = makeString(prefix, functionName.string(), "() {\n\n}");
110     else if (args.size() == 1) {
111         auto body = args.at(0).toWTFString(exec);
112         RETURN_IF_EXCEPTION(scope, nullptr);
113         program = makeString(prefix, functionName.string(), "() {\n", body, "\n}");
114     } else {
115         StringBuilder builder(StringBuilder::OverflowHandler::RecordOverflow);
116         builder.append(prefix);
117         builder.append(functionName.string());
118
119         builder.append('(');
120         auto viewWithString = args.at(0).toString(exec)->viewWithUnderlyingString(exec);
121         RETURN_IF_EXCEPTION(scope, nullptr);
122         builder.append(viewWithString.view);
123         for (size_t i = 1; !builder.hasOverflowed() && i < args.size() - 1; i++) {
124             builder.appendLiteral(", ");
125             auto viewWithString = args.at(i).toString(exec)->viewWithUnderlyingString(exec);
126             RETURN_IF_EXCEPTION(scope, nullptr);
127             builder.append(viewWithString.view);
128         }
129         if (builder.hasOverflowed()) {
130             throwOutOfMemoryError(exec, scope);
131             return nullptr;
132         }
133
134         functionConstructorParametersEndPosition = builder.length() + 1;
135         builder.appendLiteral(") {\n");
136
137         auto body = args.at(args.size() - 1).toString(exec)->viewWithUnderlyingString(exec);
138         RETURN_IF_EXCEPTION(scope, nullptr);
139         builder.append(body.view);
140         builder.appendLiteral("\n}");
141         if (builder.hasOverflowed()) {
142             throwOutOfMemoryError(exec, scope);
143             return nullptr;
144         }
145         program = builder.toString();
146     }
147
148     SourceCode source = makeSource(program, sourceOrigin, URL({ }, sourceURL), position);
149     JSObject* exception = nullptr;
150     FunctionExecutable* function = FunctionExecutable::fromGlobalCode(functionName, *exec, source, exception, overrideLineNumber, functionConstructorParametersEndPosition);
151     if (UNLIKELY(!function)) {
152         ASSERT(exception);
153         throwException(exec, scope, exception);
154         return nullptr;
155     }
156
157     Structure* structure = nullptr;
158     switch (functionConstructionMode) {
159     case FunctionConstructionMode::Function:
160         structure = JSFunction::selectStructureForNewFuncExp(globalObject, function);
161         break;
162     case FunctionConstructionMode::Generator:
163         structure = globalObject->generatorFunctionStructure();
164         break;
165     case FunctionConstructionMode::Async:
166         structure = globalObject->asyncFunctionStructure();
167         break;
168     case FunctionConstructionMode::AsyncGenerator:
169         structure = globalObject->asyncGeneratorFunctionStructure();
170         break;
171     }
172
173     Structure* subclassStructure = InternalFunction::createSubclassStructure(exec, newTarget, structure);
174     RETURN_IF_EXCEPTION(scope, nullptr);
175
176     switch (functionConstructionMode) {
177     case FunctionConstructionMode::Function:
178         return JSFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
179     case FunctionConstructionMode::Generator:
180         return JSGeneratorFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
181     case FunctionConstructionMode::Async:
182         return JSAsyncFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
183     case FunctionConstructionMode::AsyncGenerator:
184         return JSAsyncGeneratorFunction::create(vm, function, globalObject->globalScope(), subclassStructure);
185     }
186
187     ASSERT_NOT_REACHED();
188     return nullptr;
189 }
190
191 // ECMA 15.3.2 The Function Constructor
192 JSObject* constructFunction(ExecState* exec, JSGlobalObject* globalObject, const ArgList& args, FunctionConstructionMode functionConstructionMode, JSValue newTarget)
193 {
194     VM& vm = exec->vm();
195     return constructFunction(exec, globalObject, args, vm.propertyNames->anonymous, exec->callerSourceOrigin(), String(), TextPosition(), functionConstructionMode, newTarget);
196 }
197
198 } // namespace JSC