RawJSONObject.cpp (1490B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- 2 * vim: set ts=8 sts=2 et sw=2 tw=80: 3 * This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #include "builtin/RawJSONObject.h" 8 #include "js/PropertyDescriptor.h" 9 10 #include "vm/JSObject-inl.h" 11 12 using namespace js; 13 14 const JSClass RawJSONObject::class_ = { 15 "RawJSON", 16 JSCLASS_HAS_RESERVED_SLOTS(SlotCount), 17 }; 18 19 /* static */ 20 RawJSONObject* RawJSONObject::create(JSContext* cx, 21 Handle<JSString*> jsonString) { 22 // https://tc39.es/proposal-json-parse-with-source/#sec-json.rawjson 23 // Step 5 24 Rooted<RawJSONObject*> obj( 25 cx, NewObjectWithGivenProto<RawJSONObject>(cx, nullptr)); 26 if (!obj) { 27 return nullptr; 28 } 29 // Step 6 30 Rooted<PropertyKey> id(cx, NameToId(cx->names().rawJSON)); 31 Rooted<Value> jsonStringVal(cx, StringValue(jsonString)); 32 if (!NativeDefineDataProperty(cx, obj, id, jsonStringVal, JSPROP_ENUMERATE)) { 33 return nullptr; 34 } 35 return obj; 36 } 37 38 JSString* RawJSONObject::rawJSON(JSContext* cx) { 39 // RawJSONObjects are frozen on creation, so must always have a rawJSON string 40 // property. 41 PropertyKey id(NameToId(cx->names().rawJSON)); 42 JS::Value vp; 43 MOZ_ALWAYS_TRUE(GetPropertyNoGC(cx, this, ObjectValue(*this), id, &vp)); 44 MOZ_ASSERT(vp.isString()); 45 return vp.toString(); 46 }