1/*
2 * Copyright (C) 2009 Apple Inc. All rights reserved.
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#include "config.h"
27#include "JSONObject.h"
28
29#include "BooleanObject.h"
30#include "Error.h"
31#include "ExceptionHelpers.h"
32#include "JSArray.h"
33#include "JSGlobalObject.h"
34#include "LiteralParser.h"
35#include "Local.h"
36#include "LocalScope.h"
37#include "Lookup.h"
38#include "ObjectConstructor.h"
39#include "JSCInlines.h"
40#include "PropertyNameArray.h"
41#include <wtf/MathExtras.h>
42#include <wtf/text/StringBuilder.h>
43
44namespace JSC {
45
46STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(JSONObject);
47
48EncodedJSValue JSC_HOST_CALL JSONProtoFuncParse(ExecState*);
49EncodedJSValue JSC_HOST_CALL JSONProtoFuncStringify(ExecState*);
50
51}
52
53#include "JSONObject.lut.h"
54
55namespace JSC {
56
57JSONObject::JSONObject(VM& vm, Structure* structure)
58 : JSNonFinalObject(vm, structure)
59{
60}
61
62void JSONObject::finishCreation(VM& vm)
63{
64 Base::finishCreation(vm);
65 ASSERT(inherits(info()));
66
67 putDirectWithoutTransition(vm, vm.propertyNames->toStringTagSymbol, jsString(&vm, "JSON"), DontEnum | ReadOnly);
68}
69
70// PropertyNameForFunctionCall objects must be on the stack, since the JSValue that they create is not marked.
71class PropertyNameForFunctionCall {
72public:
73 PropertyNameForFunctionCall(const Identifier&);
74 PropertyNameForFunctionCall(unsigned);
75
76 JSValue value(ExecState*) const;
77
78private:
79 const Identifier* m_identifier;
80 unsigned m_number;
81 mutable JSValue m_value;
82};
83
84class Stringifier {
85 WTF_MAKE_NONCOPYABLE(Stringifier);
86public:
87 Stringifier(ExecState*, const Local<Unknown>& replacer, const Local<Unknown>& space);
88 Local<Unknown> stringify(Handle<Unknown>);
89
90 void visitAggregate(SlotVisitor&);
91
92private:
93 class Holder {
94 public:
95 Holder(VM&, JSObject*);
96
97 JSObject* object() const { return m_object.get(); }
98
99 bool appendNextProperty(Stringifier&, StringBuilder&);
100
101 private:
102 Local<JSObject> m_object;
103 const bool m_isArray;
104 bool m_isJSArray;
105 unsigned m_index;
106 unsigned m_size;
107 RefPtr<PropertyNameArrayData> m_propertyNames;
108 };
109
110 friend class Holder;
111
112 JSValue toJSON(JSValue, const PropertyNameForFunctionCall&);
113 JSValue toJSONImpl(JSValue, const PropertyNameForFunctionCall&);
114
115 enum StringifyResult { StringifyFailed, StringifySucceeded, StringifyFailedDueToUndefinedOrSymbolValue };
116 StringifyResult appendStringifiedValue(StringBuilder&, JSValue, JSObject* holder, const PropertyNameForFunctionCall&);
117
118 bool willIndent() const;
119 void indent();
120 void unindent();
121 void startNewLine(StringBuilder&) const;
122
123 ExecState* const m_exec;
124 const Local<Unknown> m_replacer;
125 bool m_usingArrayReplacer;
126 PropertyNameArray m_arrayReplacerPropertyNames;
127 CallType m_replacerCallType;
128 CallData m_replacerCallData;
129 const String m_gap;
130
131 Vector<Holder, 16, UnsafeVectorOverflow> m_holderStack;
132 String m_repeatedGap;
133 String m_indent;
134};
135
136// ------------------------------ helper functions --------------------------------
137
138static inline JSValue unwrapBoxedPrimitive(ExecState* exec, JSValue value)
139{
140 if (!value.isObject())
141 return value;
142 JSObject* object = asObject(value);
143 if (object->inherits(NumberObject::info()))
144 return jsNumber(object->toNumber(exec));
145 if (object->inherits(StringObject::info()))
146 return object->toString(exec);
147 if (object->inherits(BooleanObject::info()))
148 return object->toPrimitive(exec);
149
150 // Do not unwrap SymbolObject to Symbol. It is not performed in the spec.
151 // http://www.ecma-international.org/ecma-262/6.0/#sec-serializejsonproperty
152 return value;
153}
154
155static inline String gap(ExecState* exec, JSValue space)
156{
157 const unsigned maxGapLength = 10;
158 space = unwrapBoxedPrimitive(exec, space);
159
160 // If the space value is a number, create a gap string with that number of spaces.
161 if (space.isNumber()) {
162 double spaceCount = space.asNumber();
163 int count;
164 if (spaceCount > maxGapLength)
165 count = maxGapLength;
166 else if (!(spaceCount > 0))
167 count = 0;
168 else
169 count = static_cast<int>(spaceCount);
170 UChar spaces[maxGapLength];
171 for (int i = 0; i < count; ++i)
172 spaces[i] = ' ';
173 return String(spaces, count);
174 }
175
176 // If the space value is a string, use it as the gap string, otherwise use no gap string.
177 String spaces = space.getString(exec);
178 if (spaces.length() > maxGapLength) {
179 spaces = spaces.substringSharingImpl(0, maxGapLength);
180 }
181 return spaces;
182}
183
184// ------------------------------ PropertyNameForFunctionCall --------------------------------
185
186inline PropertyNameForFunctionCall::PropertyNameForFunctionCall(const Identifier& identifier)
187 : m_identifier(&identifier)
188{
189}
190
191inline PropertyNameForFunctionCall::PropertyNameForFunctionCall(unsigned number)
192 : m_identifier(0)
193 , m_number(number)
194{
195}
196
197JSValue PropertyNameForFunctionCall::value(ExecState* exec) const
198{
199 if (!m_value) {
200 if (m_identifier)
201 m_value = jsString(exec, m_identifier->string());
202 else
203 m_value = jsNumber(m_number);
204 }
205 return m_value;
206}
207
208// ------------------------------ Stringifier --------------------------------
209
210Stringifier::Stringifier(ExecState* exec, const Local<Unknown>& replacer, const Local<Unknown>& space)
211 : m_exec(exec)
212 , m_replacer(replacer)
213 , m_usingArrayReplacer(false)
214 , m_arrayReplacerPropertyNames(exec, PropertyNameMode::Strings)
215 , m_replacerCallType(CallTypeNone)
216 , m_gap(gap(exec, space.get()))
217{
218 if (!m_replacer.isObject())
219 return;
220
221 if (m_replacer.asObject()->inherits(JSArray::info())) {
222 m_usingArrayReplacer = true;
223 Handle<JSObject> array = m_replacer.asObject();
224 unsigned length = array->get(exec, exec->vm().propertyNames->length).toUInt32(exec);
225 for (unsigned i = 0; i < length; ++i) {
226 JSValue name = array->get(exec, i);
227 if (exec->hadException())
228 break;
229
230 if (name.isObject()) {
231 if (!asObject(name)->inherits(NumberObject::info()) && !asObject(name)->inherits(StringObject::info()))
232 continue;
233 } else if (!name.isNumber() && !name.isString())
234 continue;
235
236 m_arrayReplacerPropertyNames.add(name.toString(exec)->toIdentifier(exec));
237 }
238 return;
239 }
240
241 m_replacerCallType = m_replacer.asObject()->methodTable()->getCallData(m_replacer.asObject().get(), m_replacerCallData);
242}
243
244Local<Unknown> Stringifier::stringify(Handle<Unknown> value)
245{
246 JSObject* object = constructEmptyObject(m_exec);
247 if (m_exec->hadException())
248 return Local<Unknown>(m_exec->vm(), jsNull());
249
250 PropertyNameForFunctionCall emptyPropertyName(m_exec->vm().propertyNames->emptyIdentifier);
251 object->putDirect(m_exec->vm(), m_exec->vm().propertyNames->emptyIdentifier, value.get());
252
253 StringBuilder result;
254 if (appendStringifiedValue(result, value.get(), object, emptyPropertyName) != StringifySucceeded)
255 return Local<Unknown>(m_exec->vm(), jsUndefined());
256 if (m_exec->hadException())
257 return Local<Unknown>(m_exec->vm(), jsNull());
258
259 return Local<Unknown>(m_exec->vm(), jsString(m_exec, result.toString()));
260}
261
262ALWAYS_INLINE JSValue Stringifier::toJSON(JSValue value, const PropertyNameForFunctionCall& propertyName)
263{
264 ASSERT(!m_exec->hadException());
265 if (!value.isObject() || !asObject(value)->hasProperty(m_exec, m_exec->vm().propertyNames->toJSON))
266 return value;
267 return toJSONImpl(value, propertyName);
268}
269
270JSValue Stringifier::toJSONImpl(JSValue value, const PropertyNameForFunctionCall& propertyName)
271{
272 JSValue toJSONFunction = asObject(value)->get(m_exec, m_exec->vm().propertyNames->toJSON);
273 if (m_exec->hadException())
274 return jsNull();
275
276 if (!toJSONFunction.isObject())
277 return value;
278
279 JSObject* object = asObject(toJSONFunction);
280 CallData callData;
281 CallType callType = object->methodTable()->getCallData(object, callData);
282 if (callType == CallTypeNone)
283 return value;
284
285 MarkedArgumentBuffer args;
286 args.append(propertyName.value(m_exec));
287 return call(m_exec, object, callType, callData, value, args);
288}
289
290Stringifier::StringifyResult Stringifier::appendStringifiedValue(StringBuilder& builder, JSValue value, JSObject* holder, const PropertyNameForFunctionCall& propertyName)
291{
292 // Call the toJSON function.
293 value = toJSON(value, propertyName);
294 if (m_exec->hadException())
295 return StringifyFailed;
296
297 // Call the replacer function.
298 if (m_replacerCallType != CallTypeNone) {
299 MarkedArgumentBuffer args;
300 args.append(propertyName.value(m_exec));
301 args.append(value);
302 value = call(m_exec, m_replacer.get(), m_replacerCallType, m_replacerCallData, holder, args);
303 if (m_exec->hadException())
304 return StringifyFailed;
305 }
306
307 if ((value.isUndefined() || value.isSymbol()) && !holder->inherits(JSArray::info()))
308 return StringifyFailedDueToUndefinedOrSymbolValue;
309
310 if (value.isNull()) {
311 builder.appendLiteral("null");
312 return StringifySucceeded;
313 }
314
315 value = unwrapBoxedPrimitive(m_exec, value);
316
317 if (m_exec->hadException())
318 return StringifyFailed;
319
320 if (value.isBoolean()) {
321 if (value.isTrue())
322 builder.appendLiteral("true");
323 else
324 builder.appendLiteral("false");
325 return StringifySucceeded;
326 }
327
328 if (value.isString()) {
329 builder.appendQuotedJSONString(asString(value)->value(m_exec));
330 return StringifySucceeded;
331 }
332
333 if (value.isNumber()) {
334 if (value.isInt32())
335 builder.appendNumber(value.asInt32());
336 else {
337 double number = value.asNumber();
338 if (!std::isfinite(number))
339 builder.appendLiteral("null");
340 else
341 builder.appendECMAScriptNumber(number);
342 }
343 return StringifySucceeded;
344 }
345
346 if (!value.isObject())
347 return StringifyFailed;
348
349 JSObject* object = asObject(value);
350
351 CallData callData;
352 if (object->methodTable()->getCallData(object, callData) != CallTypeNone) {
353 if (holder->inherits(JSArray::info())) {
354 builder.appendLiteral("null");
355 return StringifySucceeded;
356 }
357 return StringifyFailedDueToUndefinedOrSymbolValue;
358 }
359
360 // Handle cycle detection, and put the holder on the stack.
361 for (unsigned i = 0; i < m_holderStack.size(); i++) {
362 if (m_holderStack[i].object() == object) {
363 m_exec->vm().throwException(m_exec, createTypeError(m_exec, ASCIILiteral("JSON.stringify cannot serialize cyclic structures.")));
364 return StringifyFailed;
365 }
366 }
367 bool holderStackWasEmpty = m_holderStack.isEmpty();
368 m_holderStack.append(Holder(m_exec->vm(), object));
369 if (!holderStackWasEmpty)
370 return StringifySucceeded;
371
372 do {
373 while (m_holderStack.last().appendNextProperty(*this, builder)) {
374 if (m_exec->hadException())
375 return StringifyFailed;
376 }
377 m_holderStack.removeLast();
378 } while (!m_holderStack.isEmpty());
379 return StringifySucceeded;
380}
381
382inline bool Stringifier::willIndent() const
383{
384 return !m_gap.isEmpty();
385}
386
387inline void Stringifier::indent()
388{
389 // Use a single shared string, m_repeatedGap, so we don't keep allocating new ones as we indent and unindent.
390 unsigned newSize = m_indent.length() + m_gap.length();
391 if (newSize > m_repeatedGap.length())
392 m_repeatedGap = makeString(m_repeatedGap, m_gap);
393 ASSERT(newSize <= m_repeatedGap.length());
394 m_indent = m_repeatedGap.substringSharingImpl(0, newSize);
395}
396
397inline void Stringifier::unindent()
398{
399 ASSERT(m_indent.length() >= m_gap.length());
400 m_indent = m_repeatedGap.substringSharingImpl(0, m_indent.length() - m_gap.length());
401}
402
403inline void Stringifier::startNewLine(StringBuilder& builder) const
404{
405 if (m_gap.isEmpty())
406 return;
407 builder.append('\n');
408 builder.append(m_indent);
409}
410
411inline Stringifier::Holder::Holder(VM& vm, JSObject* object)
412 : m_object(vm, object)
413 , m_isArray(object->inherits(JSArray::info()))
414 , m_index(0)
415#ifndef NDEBUG
416 , m_size(0)
417#endif
418{
419}
420
421bool Stringifier::Holder::appendNextProperty(Stringifier& stringifier, StringBuilder& builder)
422{
423 ASSERT(m_index <= m_size);
424
425 ExecState* exec = stringifier.m_exec;
426
427 // First time through, initialize.
428 if (!m_index) {
429 if (m_isArray) {
430 m_isJSArray = isJSArray(m_object.get());
431 if (m_isJSArray)
432 m_size = asArray(m_object.get())->length();
433 else
434 m_size = m_object->get(exec, exec->vm().propertyNames->length).toUInt32(exec);
435 builder.append('[');
436 } else {
437 if (stringifier.m_usingArrayReplacer)
438 m_propertyNames = stringifier.m_arrayReplacerPropertyNames.data();
439 else {
440 PropertyNameArray objectPropertyNames(exec, PropertyNameMode::Strings);
441 m_object->methodTable()->getOwnPropertyNames(m_object.get(), exec, objectPropertyNames, EnumerationMode());
442 m_propertyNames = objectPropertyNames.releaseData();
443 }
444 m_size = m_propertyNames->propertyNameVector().size();
445 builder.append('{');
446 }
447 stringifier.indent();
448 }
449
450 // Last time through, finish up and return false.
451 if (m_index == m_size) {
452 stringifier.unindent();
453 if (m_size && builder[builder.length() - 1] != '{')
454 stringifier.startNewLine(builder);
455 builder.append(m_isArray ? ']' : '}');
456 return false;
457 }
458
459 // Handle a single element of the array or object.
460 unsigned index = m_index++;
461 unsigned rollBackPoint = 0;
462 StringifyResult stringifyResult;
463 if (m_isArray) {
464 // Get the value.
465 JSValue value;
466 if (m_isJSArray && asArray(m_object.get())->canGetIndexQuickly(index))
467 value = asArray(m_object.get())->getIndexQuickly(index);
468 else {
469 PropertySlot slot(m_object.get(), PropertySlot::InternalMethodType::Get);
470 if (m_object->methodTable()->getOwnPropertySlotByIndex(m_object.get(), exec, index, slot)) {
471 value = slot.getValue(exec, index);
472 if (exec->hadException())
473 return false;
474 } else
475 value = jsUndefined();
476 }
477
478 // Append the separator string.
479 if (index)
480 builder.append(',');
481 stringifier.startNewLine(builder);
482
483 // Append the stringified value.
484 stringifyResult = stringifier.appendStringifiedValue(builder, value, m_object.get(), index);
485 } else {
486 // Get the value.
487 PropertySlot slot(m_object.get(), PropertySlot::InternalMethodType::Get);
488 Identifier& propertyName = m_propertyNames->propertyNameVector()[index];
489 if (!m_object->methodTable()->getOwnPropertySlot(m_object.get(), exec, propertyName, slot))
490 return true;
491 JSValue value = slot.getValue(exec, propertyName);
492 if (exec->hadException())
493 return false;
494
495 rollBackPoint = builder.length();
496
497 // Append the separator string.
498 if (builder[rollBackPoint - 1] != '{')
499 builder.append(',');
500 stringifier.startNewLine(builder);
501
502 // Append the property name.
503 builder.appendQuotedJSONString(propertyName.string());
504 builder.append(':');
505 if (stringifier.willIndent())
506 builder.append(' ');
507
508 // Append the stringified value.
509 stringifyResult = stringifier.appendStringifiedValue(builder, value, m_object.get(), propertyName);
510 }
511
512 // From this point on, no access to the this pointer or to any members, because the
513 // Holder object may have moved if the call to stringify pushed a new Holder onto
514 // m_holderStack.
515
516 switch (stringifyResult) {
517 case StringifyFailed:
518 builder.appendLiteral("null");
519 break;
520 case StringifySucceeded:
521 break;
522 case StringifyFailedDueToUndefinedOrSymbolValue:
523 // This only occurs when get an undefined value or a symbol value for
524 // an object property. In this case we don't want the separator and
525 // property name that we already appended, so roll back.
526 builder.resize(rollBackPoint);
527 break;
528 }
529
530 return true;
531}
532
533// ------------------------------ JSONObject --------------------------------
534
535const ClassInfo JSONObject::s_info = { "JSON", &JSNonFinalObject::s_info, &jsonTable, CREATE_METHOD_TABLE(JSONObject) };
536
537/* Source for JSONObject.lut.h
538@begin jsonTable
539 parse JSONProtoFuncParse DontEnum|Function 2
540 stringify JSONProtoFuncStringify DontEnum|Function 3
541@end
542*/
543
544// ECMA 15.8
545
546bool JSONObject::getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName propertyName, PropertySlot& slot)
547{
548 return getStaticFunctionSlot<JSObject>(exec, jsonTable, jsCast<JSONObject*>(object), propertyName, slot);
549}
550
551class Walker {
552public:
553 Walker(ExecState* exec, Handle<JSObject> function, CallType callType, CallData callData)
554 : m_exec(exec)
555 , m_function(exec->vm(), function)
556 , m_callType(callType)
557 , m_callData(callData)
558 {
559 }
560 JSValue walk(JSValue unfiltered);
561private:
562 JSValue callReviver(JSObject* thisObj, JSValue property, JSValue unfiltered)
563 {
564 MarkedArgumentBuffer args;
565 args.append(property);
566 args.append(unfiltered);
567 return call(m_exec, m_function.get(), m_callType, m_callData, thisObj, args);
568 }
569
570 friend class Holder;
571
572 ExecState* m_exec;
573 Local<JSObject> m_function;
574 CallType m_callType;
575 CallData m_callData;
576};
577
578// We clamp recursion well beyond anything reasonable.
579static const unsigned maximumFilterRecursion = 40000;
580enum WalkerState { StateUnknown, ArrayStartState, ArrayStartVisitMember, ArrayEndVisitMember,
581 ObjectStartState, ObjectStartVisitMember, ObjectEndVisitMember };
582NEVER_INLINE JSValue Walker::walk(JSValue unfiltered)
583{
584 Vector<PropertyNameArray, 16, UnsafeVectorOverflow> propertyStack;
585 Vector<uint32_t, 16, UnsafeVectorOverflow> indexStack;
586 LocalStack<JSObject, 16> objectStack(m_exec->vm());
587 LocalStack<JSArray, 16> arrayStack(m_exec->vm());
588
589 Vector<WalkerState, 16, UnsafeVectorOverflow> stateStack;
590 WalkerState state = StateUnknown;
591 JSValue inValue = unfiltered;
592 JSValue outValue = jsNull();
593
594 while (1) {
595 switch (state) {
596 arrayStartState:
597 case ArrayStartState: {
598 ASSERT(inValue.isObject());
599 ASSERT(isJSArray(asObject(inValue)) || asObject(inValue)->inherits(JSArray::info()));
600 if (objectStack.size() + arrayStack.size() > maximumFilterRecursion)
601 return throwStackOverflowError(m_exec);
602
603 JSArray* array = asArray(inValue);
604 arrayStack.push(array);
605 indexStack.append(0);
606 }
607 arrayStartVisitMember:
608 FALLTHROUGH;
609 case ArrayStartVisitMember: {
610 JSArray* array = arrayStack.peek();
611 uint32_t index = indexStack.last();
612 if (index == array->length()) {
613 outValue = array;
614 arrayStack.pop();
615 indexStack.removeLast();
616 break;
617 }
618 if (isJSArray(array) && array->canGetIndexQuickly(index))
619 inValue = array->getIndexQuickly(index);
620 else {
621 PropertySlot slot(array, PropertySlot::InternalMethodType::Get);
622 if (array->methodTable()->getOwnPropertySlotByIndex(array, m_exec, index, slot))
623 inValue = slot.getValue(m_exec, index);
624 else
625 inValue = jsUndefined();
626 }
627
628 if (inValue.isObject()) {
629 stateStack.append(ArrayEndVisitMember);
630 goto stateUnknown;
631 } else
632 outValue = inValue;
633 FALLTHROUGH;
634 }
635 case ArrayEndVisitMember: {
636 JSArray* array = arrayStack.peek();
637 JSValue filteredValue = callReviver(array, jsString(m_exec, String::number(indexStack.last())), outValue);
638 if (filteredValue.isUndefined())
639 array->methodTable()->deletePropertyByIndex(array, m_exec, indexStack.last());
640 else
641 array->putDirectIndex(m_exec, indexStack.last(), filteredValue);
642 if (m_exec->hadException())
643 return jsNull();
644 indexStack.last()++;
645 goto arrayStartVisitMember;
646 }
647 objectStartState:
648 case ObjectStartState: {
649 ASSERT(inValue.isObject());
650 ASSERT(!isJSArray(asObject(inValue)) && !asObject(inValue)->inherits(JSArray::info()));
651 if (objectStack.size() + arrayStack.size() > maximumFilterRecursion)
652 return throwStackOverflowError(m_exec);
653
654 JSObject* object = asObject(inValue);
655 objectStack.push(object);
656 indexStack.append(0);
657 propertyStack.append(PropertyNameArray(m_exec, PropertyNameMode::Strings));
658 object->methodTable()->getOwnPropertyNames(object, m_exec, propertyStack.last(), EnumerationMode());
659 }
660 objectStartVisitMember:
661 FALLTHROUGH;
662 case ObjectStartVisitMember: {
663 JSObject* object = objectStack.peek();
664 uint32_t index = indexStack.last();
665 PropertyNameArray& properties = propertyStack.last();
666 if (index == properties.size()) {
667 outValue = object;
668 objectStack.pop();
669 indexStack.removeLast();
670 propertyStack.removeLast();
671 break;
672 }
673 PropertySlot slot(object, PropertySlot::InternalMethodType::Get);
674 if (object->methodTable()->getOwnPropertySlot(object, m_exec, properties[index], slot))
675 inValue = slot.getValue(m_exec, properties[index]);
676 else
677 inValue = jsUndefined();
678
679 // The holder may be modified by the reviver function so any lookup may throw
680 if (m_exec->hadException())
681 return jsNull();
682
683 if (inValue.isObject()) {
684 stateStack.append(ObjectEndVisitMember);
685 goto stateUnknown;
686 } else
687 outValue = inValue;
688 FALLTHROUGH;
689 }
690 case ObjectEndVisitMember: {
691 JSObject* object = objectStack.peek();
692 Identifier prop = propertyStack.last()[indexStack.last()];
693 PutPropertySlot slot(object);
694 JSValue filteredValue = callReviver(object, jsString(m_exec, prop.string()), outValue);
695 if (filteredValue.isUndefined())
696 object->methodTable()->deleteProperty(object, m_exec, prop);
697 else
698 object->methodTable()->put(object, m_exec, prop, filteredValue, slot);
699 if (m_exec->hadException())
700 return jsNull();
701 indexStack.last()++;
702 goto objectStartVisitMember;
703 }
704 stateUnknown:
705 case StateUnknown:
706 if (!inValue.isObject()) {
707 outValue = inValue;
708 break;
709 }
710 JSObject* object = asObject(inValue);
711 if (isJSArray(object) || object->inherits(JSArray::info()))
712 goto arrayStartState;
713 goto objectStartState;
714 }
715 if (stateStack.isEmpty())
716 break;
717
718 state = stateStack.last();
719 stateStack.removeLast();
720 }
721 JSObject* finalHolder = constructEmptyObject(m_exec);
722 PutPropertySlot slot(finalHolder);
723 finalHolder->methodTable()->put(finalHolder, m_exec, m_exec->vm().propertyNames->emptyIdentifier, outValue, slot);
724 return callReviver(finalHolder, jsEmptyString(m_exec), outValue);
725}
726
727// ECMA-262 v5 15.12.2
728EncodedJSValue JSC_HOST_CALL JSONProtoFuncParse(ExecState* exec)
729{
730 if (!exec->argumentCount())
731 return throwVMError(exec, createError(exec, ASCIILiteral("JSON.parse requires at least one parameter")));
732 JSString::SafeView source = exec->uncheckedArgument(0).toString(exec)->view(exec);
733 if (exec->hadException())
734 return JSValue::encode(jsNull());
735
736 JSValue unfiltered;
737 LocalScope scope(exec->vm());
738 if (source.is8Bit()) {
739 LiteralParser<LChar> jsonParser(exec, source.characters8(), source.length(), StrictJSON);
740 unfiltered = jsonParser.tryLiteralParse();
741 if (!unfiltered)
742 return throwVMError(exec, createSyntaxError(exec, jsonParser.getErrorMessage()));
743 } else {
744 LiteralParser<UChar> jsonParser(exec, source.characters16(), source.length(), StrictJSON);
745 unfiltered = jsonParser.tryLiteralParse();
746 if (!unfiltered)
747 return throwVMError(exec, createSyntaxError(exec, jsonParser.getErrorMessage()));
748 }
749
750 if (exec->argumentCount() < 2)
751 return JSValue::encode(unfiltered);
752
753 JSValue function = exec->uncheckedArgument(1);
754 CallData callData;
755 CallType callType = getCallData(function, callData);
756 if (callType == CallTypeNone)
757 return JSValue::encode(unfiltered);
758 return JSValue::encode(Walker(exec, Local<JSObject>(exec->vm(), asObject(function)), callType, callData).walk(unfiltered));
759}
760
761// ECMA-262 v5 15.12.3
762EncodedJSValue JSC_HOST_CALL JSONProtoFuncStringify(ExecState* exec)
763{
764 if (!exec->argumentCount())
765 return throwVMError(exec, createError(exec, ASCIILiteral("No input to stringify")));
766 LocalScope scope(exec->vm());
767 Local<Unknown> value(exec->vm(), exec->uncheckedArgument(0));
768 Local<Unknown> replacer(exec->vm(), exec->argument(1));
769 Local<Unknown> space(exec->vm(), exec->argument(2));
770 JSValue result = Stringifier(exec, replacer, space).stringify(value).get();
771 return JSValue::encode(result);
772}
773
774JSValue JSONParse(ExecState* exec, const String& json)
775{
776 LocalScope scope(exec->vm());
777
778 if (json.is8Bit()) {
779 LiteralParser<LChar> jsonParser(exec, json.characters8(), json.length(), StrictJSON);
780 return jsonParser.tryLiteralParse();
781 }
782
783 LiteralParser<UChar> jsonParser(exec, json.characters16(), json.length(), StrictJSON);
784 return jsonParser.tryLiteralParse();
785}
786
787String JSONStringify(ExecState* exec, JSValue value, unsigned indent)
788{
789 LocalScope scope(exec->vm());
790 Local<Unknown> result = Stringifier(exec, Local<Unknown>(exec->vm(), jsNull()), Local<Unknown>(exec->vm(), jsNumber(indent))).stringify(Local<Unknown>(exec->vm(), value));
791 if (result.isUndefinedOrNull())
792 return String();
793 return result.getString(exec);
794}
795
796} // namespace JSC
797