builtins-function.cc 11.7 KB
Newer Older
1 2 3 4
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/api/api-inl.h"
6
#include "src/builtins/builtins-utils-inl.h"
7
#include "src/builtins/builtins.h"
8 9
#include "src/codegen/code-factory.h"
#include "src/codegen/compiler.h"
10
#include "src/logging/counters.h"
11
#include "src/numbers/conversions.h"
12
#include "src/objects/api-callbacks.h"
13
#include "src/objects/lookup.h"
14
#include "src/objects/objects-inl.h"
15
#include "src/strings/string-builder-inl.h"
16 17 18 19 20 21 22 23 24 25 26 27 28 29

namespace v8 {
namespace internal {

namespace {

// ES6 section 19.2.1.1.1 CreateDynamicFunction
MaybeHandle<Object> CreateDynamicFunction(Isolate* isolate,
                                          BuiltinArguments args,
                                          const char* token) {
  // Compute number of arguments, ignoring the receiver.
  DCHECK_LE(1, args.length());
  int const argc = args.length() - 1;

30
  Handle<JSFunction> target = args.target();
31 32
  Handle<JSObject> target_global_proxy(target->global_proxy(), isolate);

33
  if (!Builtins::AllowDynamicFunction(isolate, target, target_global_proxy)) {
34
    isolate->CountUsage(v8::Isolate::kFunctionConstructorReturnedUndefined);
35 36 37 38 39
    // TODO(verwaest): We would like to throw using the calling context instead
    // of the entered context but we don't currently have access to that.
    HandleScopeImplementer* impl = isolate->handle_scope_implementer();
    SaveAndSwitchContext save(
        isolate, impl->LastEnteredOrMicrotaskContext()->native_context());
40
    THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kNoAccess), Object);
41 42 43 44
  }

  // Build the source string.
  Handle<String> source;
45
  int parameters_end_pos = kNoSourcePosition;
46 47 48 49
  {
    IncrementalStringBuilder builder(isolate);
    builder.AppendCharacter('(');
    builder.AppendCString(token);
50
    builder.AppendCString(" anonymous(");
51 52 53 54 55 56
    bool parenthesis_in_arg_string = false;
    if (argc > 1) {
      for (int i = 1; i < argc; ++i) {
        if (i > 1) builder.AppendCharacter(',');
        Handle<String> param;
        ASSIGN_RETURN_ON_EXCEPTION(
57
            isolate, param, Object::ToString(isolate, args.at(i)), Object);
58
        param = String::Flatten(isolate, param);
59 60 61
        builder.AppendString(param);
      }
    }
62 63
    builder.AppendCharacter('\n');
    parameters_end_pos = builder.Length();
64 65 66 67
    builder.AppendCString(") {\n");
    if (argc > 0) {
      Handle<String> body;
      ASSIGN_RETURN_ON_EXCEPTION(
68
          isolate, body, Object::ToString(isolate, args.at(argc)), Object);
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
      builder.AppendString(body);
    }
    builder.AppendCString("\n})");
    ASSIGN_RETURN_ON_EXCEPTION(isolate, source, builder.Finish(), Object);

    // The SyntaxError must be thrown after all the (observable) ToString
    // conversions are done.
    if (parenthesis_in_arg_string) {
      THROW_NEW_ERROR(isolate,
                      NewSyntaxError(MessageTemplate::kParenthesisInArgString),
                      Object);
    }
  }

  // Compile the string in the constructor and not a helper so that errors to
  // come from here.
  Handle<JSFunction> function;
  {
87 88 89 90 91 92
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, function,
        Compiler::GetFunctionFromString(
            handle(target->native_context(), isolate), source,
            ONLY_SINGLE_FUNCTION_LITERAL, parameters_end_pos),
        Object);
93 94 95 96 97 98
    Handle<Object> result;
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, result,
        Execution::Call(isolate, function, target_global_proxy, 0, nullptr),
        Object);
    function = Handle<JSFunction>::cast(result);
99
    function->shared().set_name_should_print_as_anonymous(true);
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
  }

  // If new.target is equal to target then the function created
  // is already correctly setup and nothing else should be done
  // here. But if new.target is not equal to target then we are
  // have a Function builtin subclassing case and therefore the
  // function has wrong initial map. To fix that we create a new
  // function object with correct initial map.
  Handle<Object> unchecked_new_target = args.new_target();
  if (!unchecked_new_target->IsUndefined(isolate) &&
      !unchecked_new_target.is_identical_to(target)) {
    Handle<JSReceiver> new_target =
        Handle<JSReceiver>::cast(unchecked_new_target);
    Handle<Map> initial_map;
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, initial_map,
        JSFunction::GetDerivedMap(isolate, target, new_target), Object);

    Handle<SharedFunctionInfo> shared_info(function->shared(), isolate);
119
    Handle<Map> map = Map::AsLanguageMode(isolate, initial_map, shared_info);
120 121 122

    Handle<Context> context(function->context(), isolate);
    function = isolate->factory()->NewFunctionFromSharedFunctionInfo(
123
        map, shared_info, context, AllocationType::kYoung);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
  }
  return function;
}

}  // namespace

// ES6 section 19.2.1.1 Function ( p1, p2, ... , pn, body )
BUILTIN(FunctionConstructor) {
  HandleScope scope(isolate);
  Handle<Object> result;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, result, CreateDynamicFunction(isolate, args, "function"));
  return *result;
}

// ES6 section 25.2.1.1 GeneratorFunction (p1, p2, ... , pn, body)
BUILTIN(GeneratorFunctionConstructor) {
  HandleScope scope(isolate);
  RETURN_RESULT_OR_FAILURE(isolate,
                           CreateDynamicFunction(isolate, args, "function*"));
}

BUILTIN(AsyncFunctionConstructor) {
  HandleScope scope(isolate);
  Handle<Object> maybe_func;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, maybe_func,
      CreateDynamicFunction(isolate, args, "async function"));
  if (!maybe_func->IsJSFunction()) return *maybe_func;

  // Do not lazily compute eval position for AsyncFunction, as they may not be
  // determined after the function is resumed.
  Handle<JSFunction> func = Handle<JSFunction>::cast(maybe_func);
157
  Handle<Script> script =
158
      handle(Script::cast(func->shared().script()), isolate);
159
  int position = Script::GetEvalPosition(isolate, script);
160 161 162 163 164
  USE(position);

  return *func;
}

165 166 167 168 169 170 171 172 173 174 175
BUILTIN(AsyncGeneratorFunctionConstructor) {
  HandleScope scope(isolate);
  Handle<Object> maybe_func;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, maybe_func,
      CreateDynamicFunction(isolate, args, "async function*"));
  if (!maybe_func->IsJSFunction()) return *maybe_func;

  // Do not lazily compute eval position for AsyncFunction, as they may not be
  // determined after the function is resumed.
  Handle<JSFunction> func = Handle<JSFunction>::cast(maybe_func);
176
  Handle<Script> script =
177
      handle(Script::cast(func->shared().script()), isolate);
178
  int position = Script::GetEvalPosition(isolate, script);
179 180 181 182 183
  USE(position);

  return *func;
}

184 185
namespace {

186
Object DoFunctionBind(Isolate* isolate, BuiltinArguments args) {
187 188 189 190 191 192 193 194 195 196 197 198
  HandleScope scope(isolate);
  DCHECK_LE(1, args.length());
  if (!args.receiver()->IsCallable()) {
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kFunctionBind));
  }

  // Allocate the bound function with the given {this_arg} and {args}.
  Handle<JSReceiver> target = args.at<JSReceiver>(0);
  Handle<Object> this_arg = isolate->factory()->undefined_value();
  ScopedVector<Handle<Object>> argv(std::max(0, args.length() - 2));
  if (args.length() > 1) {
199
    this_arg = args.at(1);
200
    for (int i = 2; i < args.length(); ++i) {
201
      argv[i - 2] = args.at(i);
202 203 204 205 206 207 208
    }
  }
  Handle<JSBoundFunction> function;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, function,
      isolate->factory()->NewJSBoundFunction(target, this_arg, argv));

209 210 211
  LookupIterator length_lookup(isolate, target,
                               isolate->factory()->length_string(), target,
                               LookupIterator::OWN);
212 213 214 215 216 217 218
  // Setup the "length" property based on the "length" of the {target}.
  // If the targets length is the default JSFunction accessor, we can keep the
  // accessor that's installed by default on the JSBoundFunction. It lazily
  // computes the value from the underlying internal length.
  if (!target->IsJSFunction() ||
      length_lookup.state() != LookupIterator::ACCESSOR ||
      !length_lookup.GetAccessors()->IsAccessorInfo()) {
219
    Handle<Object> length(Smi::zero(), isolate);
220 221
    Maybe<PropertyAttributes> attributes =
        JSReceiver::GetPropertyAttributes(&length_lookup);
222
    if (attributes.IsNothing()) return ReadOnlyRoots(isolate).exception();
223 224 225 226 227 228 229 230 231
    if (attributes.FromJust() != ABSENT) {
      Handle<Object> target_length;
      ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, target_length,
                                         Object::GetProperty(&length_lookup));
      if (target_length->IsNumber()) {
        length = isolate->factory()->NewNumber(std::max(
            0.0, DoubleToInteger(target_length->Number()) - argv.length()));
      }
    }
232 233
    LookupIterator it(isolate, function, isolate->factory()->length_string(),
                      function);
234 235 236 237 238 239 240
    DCHECK_EQ(LookupIterator::ACCESSOR, it.state());
    RETURN_FAILURE_ON_EXCEPTION(isolate,
                                JSObject::DefineOwnPropertyIgnoreAttributes(
                                    &it, length, it.property_attributes()));
  }

  // Setup the "name" property based on the "name" of the {target}.
241
  // If the target's name is the default JSFunction accessor, we can keep the
242 243
  // accessor that's installed by default on the JSBoundFunction. It lazily
  // computes the value from the underlying internal name.
244 245
  LookupIterator name_lookup(isolate, target, isolate->factory()->name_string(),
                             target);
246 247
  if (!target->IsJSFunction() ||
      name_lookup.state() != LookupIterator::ACCESSOR ||
248 249
      !name_lookup.GetAccessors()->IsAccessorInfo() ||
      (name_lookup.IsFound() && !name_lookup.HolderIsReceiver())) {
250 251 252 253 254 255 256
    Handle<Object> target_name;
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, target_name,
                                       Object::GetProperty(&name_lookup));
    Handle<String> name;
    if (target_name->IsString()) {
      ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
          isolate, name,
257
          Name::ToFunctionName(isolate, Handle<String>::cast(target_name)));
258 259 260 261 262 263
      ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
          isolate, name, isolate->factory()->NewConsString(
                             isolate->factory()->bound__string(), name));
    } else {
      name = isolate->factory()->bound__string();
    }
264
    LookupIterator it(isolate, function, isolate->factory()->name_string());
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    DCHECK_EQ(LookupIterator::ACCESSOR, it.state());
    RETURN_FAILURE_ON_EXCEPTION(isolate,
                                JSObject::DefineOwnPropertyIgnoreAttributes(
                                    &it, name, it.property_attributes()));
  }
  return *function;
}

}  // namespace

// ES6 section 19.2.3.2 Function.prototype.bind ( thisArg, ...args )
BUILTIN(FunctionPrototypeBind) { return DoFunctionBind(isolate, args); }

// ES6 section 19.2.3.5 Function.prototype.toString ( )
BUILTIN(FunctionPrototypeToString) {
  HandleScope scope(isolate);
  Handle<Object> receiver = args.receiver();
  if (receiver->IsJSBoundFunction()) {
    return *JSBoundFunction::ToString(Handle<JSBoundFunction>::cast(receiver));
284 285
  }
  if (receiver->IsJSFunction()) {
286 287
    return *JSFunction::ToString(Handle<JSFunction>::cast(receiver));
  }
288 289
  // With the revised toString behavior, all callable objects are valid
  // receivers for this method.
290
  if (receiver->IsJSReceiver() &&
291
      JSReceiver::cast(*receiver).map().is_callable()) {
292
    return ReadOnlyRoots(isolate).function_native_code_string();
293
  }
294 295 296
  THROW_NEW_ERROR_RETURN_FAILURE(
      isolate, NewTypeError(MessageTemplate::kNotGeneric,
                            isolate->factory()->NewStringFromAsciiChecked(
297 298
                                "Function.prototype.toString"),
                            isolate->factory()->Function_string()));
299 300 301 302
}

}  // namespace internal
}  // namespace v8