builtins-symbol.cc 2.31 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/builtins/builtins-utils-inl.h"
6
#include "src/builtins/builtins.h"
7
#include "src/heap/heap-inl.h"  // For public_symbol_table().
8
#include "src/logging/counters.h"
9
#include "src/objects/objects-inl.h"
10 11 12 13 14

namespace v8 {
namespace internal {

// -----------------------------------------------------------------------------
15
// ES #sec-symbol-objects
16

17
// ES #sec-symbol-constructor
18 19
BUILTIN(SymbolConstructor) {
  HandleScope scope(isolate);
20
  if (!args.new_target()->IsUndefined(isolate)) {  // [[Construct]]
21 22 23
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kNotConstructor,
                              isolate->factory()->Symbol_string()));
24
  }
25 26 27 28 29 30
  // [[Call]]
  Handle<Symbol> result = isolate->factory()->NewSymbol();
  Handle<Object> description = args.atOrUndefined(isolate, 1);
  if (!description->IsUndefined(isolate)) {
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, description,
                                       Object::ToString(isolate, description));
31
    result->set_description(String::cast(*description));
32 33
  }
  return *result;
34 35
}

36 37 38 39 40 41 42
// ES6 section 19.4.2.1 Symbol.for.
BUILTIN(SymbolFor) {
  HandleScope scope(isolate);
  Handle<Object> key_obj = args.atOrUndefined(isolate, 1);
  Handle<String> key;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, key,
                                     Object::ToString(isolate, key_obj));
43
  return *isolate->SymbolFor(RootIndex::kPublicSymbolTable, key, false);
44 45 46 47 48 49 50 51 52 53 54
}

// ES6 section 19.4.2.5 Symbol.keyFor.
BUILTIN(SymbolKeyFor) {
  HandleScope scope(isolate);
  Handle<Object> obj = args.atOrUndefined(isolate, 1);
  if (!obj->IsSymbol()) {
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kSymbolKeyFor, obj));
  }
  Handle<Symbol> symbol = Handle<Symbol>::cast(obj);
55
  DisallowGarbageCollection no_gc;
56
  Object result;
57
  if (symbol->is_in_public_symbol_table()) {
58
    result = symbol->description();
59
    DCHECK(result.IsString());
60
  } else {
61
    result = ReadOnlyRoots(isolate).undefined_value();
62
  }
63
  DCHECK_EQ(isolate->heap()->public_symbol_table().SlowReverseLookup(*symbol),
64 65 66 67
            result);
  return result;
}

68 69
}  // namespace internal
}  // namespace v8