1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sw=4 et tw=99:
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
17 * The Original Code is SpiderMonkey JSON.
19 * The Initial Developer of the Original Code is
20 * Mozilla Corporation.
21 * Portions created by the Initial Developer are Copyright (C) 1998-1999
22 * the Initial Developer. All Rights Reserved.
25 * Robert Sayre <sayrer@gmail.com>
26 * Dave Camp <dcamp@mozilla.com>
28 * Alternatively, the contents of this file may be used under the terms of
29 * either of the GNU General Public License Version 2 or later (the "GPL"),
30 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
31 * in which case the provisions of the GPL or the LGPL are applicable instead
32 * of those above. If you wish to allow use of your version of this file only
33 * under the terms of either the GPL or the LGPL, and not to allow others to
34 * use your version of this file under the terms of the MPL, indicate your
35 * decision by deleting the provisions above and replace them with the notice
36 * and other provisions required by the GPL or the LGPL. If you do not delete
37 * the provisions above, a recipient may use your version of this file under
38 * the terms of any one of the MPL, the GPL or the LGPL.
40 * ***** END LICENSE BLOCK ***** */
65 #include "jsatominlines.h"
66 #include "jsobjinlines.h"
69 using namespace js::gc;
73 #pragma warning(disable:4351)
78 JSONParser(JSContext *cx)
79 : hexChar(), numHex(), statep(), stateStack(), rootVal(), objectStack(),
80 objectKey(cx), buffer(cx), suppressErrors(false)
83 /* Used while handling \uNNNN in strings */
87 JSONParserState *statep;
88 JSONParserState stateStack[JSON_MAX_DEPTH];
90 JSObject *objectStack;
91 js::Vector<jschar, 8> objectKey;
92 js::Vector<jschar, 8> buffer;
100 Class js_JSONClass = {
102 JSCLASS_HAS_CACHED_PROTO(JSProto_JSON),
103 PropertyStub, /* addProperty */
104 PropertyStub, /* delProperty */
105 PropertyStub, /* getProperty */
106 StrictPropertyStub, /* setProperty */
113 js_json_parse(JSContext *cx, uintN argc, Value *vp)
116 Value *argv = vp + 2;
117 AutoValueRooter reviver(cx);
119 if (!JS_ConvertArguments(cx, argc, Jsvalify(argv), "S / v", &s, reviver.addr()))
122 JSLinearString *linearStr = s->ensureLinear(cx);
126 JSONParser *jp = js_BeginJSONParse(cx, vp);
127 JSBool ok = jp != NULL;
129 const jschar *chars = linearStr->chars();
130 size_t length = linearStr->length();
131 ok = js_ConsumeJSONText(cx, jp, chars, length);
132 ok &= !!js_FinishJSONParse(cx, jp, reviver.value());
139 js_json_stringify(JSContext *cx, uintN argc, Value *vp)
141 Value *argv = vp + 2;
142 AutoValueRooter space(cx);
143 AutoObjectRooter replacer(cx);
145 // Must throw an Error if there isn't a first arg
146 if (!JS_ConvertArguments(cx, argc, Jsvalify(argv), "v / o v", vp, replacer.addr(), space.addr()))
151 if (!js_Stringify(cx, vp, replacer.object(), space.value(), sb))
154 // XXX This can never happen to nsJSON.cpp, but the JSON object
155 // needs to support returning undefined. So this is a little awkward
156 // for the API, because we want to support streaming writers.
158 JSString *str = sb.finishString();
170 js_TryJSON(JSContext *cx, Value *vp)
172 // Checks whether the return value implements toJSON()
175 if (vp->isObject()) {
176 JSObject *obj = &vp->toObject();
177 ok = js_TryMethod(cx, obj, cx->runtime->atomState.toJSONAtom, 0, NULL, vp);
184 static const char quote = '\"';
185 static const char backslash = '\\';
186 static const char unicodeEscape[] = "\\u00";
189 write_string(JSContext *cx, StringBuffer &sb, const jschar *buf, uint32 len)
191 if (!sb.append(quote))
196 for (i = 0; i < len; ++i) {
197 if (buf[i] == quote || buf[i] == backslash) {
198 if (!sb.append(&buf[mark], i - mark) || !sb.append(backslash) ||
199 !sb.append(buf[i])) {
203 } else if (buf[i] <= 31 || buf[i] == 127) {
204 if (!sb.append(&buf[mark], i - mark) ||
205 !sb.append(unicodeEscape)) {
209 size_t len = JS_snprintf(ubuf, sizeof(ubuf), "%.2x", buf[i]);
212 size_t wbufSize = JS_ARRAY_LENGTH(wbuf);
213 if (!js_InflateStringToBuffer(cx, ubuf, len, wbuf, &wbufSize) ||
214 !sb.append(wbuf, wbufSize)) {
221 if (mark < len && !sb.append(&buf[mark], len - mark))
224 return sb.append(quote);
227 class StringifyContext
230 StringifyContext(JSContext *cx, StringBuffer &sb, JSObject *replacer)
231 : sb(sb), gap(cx), replacer(replacer), depth(0), objectStack(cx)
234 bool initializeGap(JSContext *cx, const Value &space) {
235 AutoValueRooter gapValue(cx, space);
237 if (space.isObject()) {
238 JSObject &obj = space.toObject();
239 Class *clasp = obj.getClass();
240 if (clasp == &js_NumberClass || clasp == &js_StringClass)
241 *gapValue.addr() = obj.getPrimitiveThis();
244 if (gapValue.value().isString()) {
245 if (!ValueToStringBuffer(cx, gapValue.value(), gap))
247 if (gap.length() > 10)
249 } else if (gapValue.value().isNumber()) {
250 jsdouble d = gapValue.value().isInt32()
251 ? gapValue.value().toInt32()
252 : js_DoubleToInteger(gapValue.value().toDouble());
254 if (d >= 1 && !gap.appendN(' ', uint32(d)))
261 bool initializeStack() {
262 return objectStack.init(16);
266 ~StringifyContext() { JS_ASSERT(objectStack.empty()); }
273 HashSet<JSObject *> objectStack;
276 static JSBool CallReplacerFunction(JSContext *cx, jsid id, JSObject *holder,
277 StringifyContext *scx, Value *vp);
278 static JSBool Str(JSContext *cx, jsid id, JSObject *holder,
279 StringifyContext *scx, Value *vp, bool callReplacer = true);
282 WriteIndent(JSContext *cx, StringifyContext *scx, uint32 limit)
284 if (!scx->gap.empty()) {
285 if (!scx->sb.append('\n'))
287 for (uint32 i = 0; i < limit; i++) {
288 if (!scx->sb.append(scx->gap.begin(), scx->gap.end()))
299 CycleDetector(StringifyContext *scx, JSObject *obj)
300 : objectStack(scx->objectStack), obj(obj) {
303 bool init(JSContext *cx) {
304 HashSet<JSObject *>::AddPtr ptr = objectStack.lookupForAdd(obj);
306 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CYCLIC_VALUE, js_object_str);
309 return objectStack.add(ptr, obj);
313 objectStack.remove(obj);
317 HashSet<JSObject *> &objectStack;
322 JO(JSContext *cx, Value *vp, StringifyContext *scx)
324 JSObject *obj = &vp->toObject();
326 CycleDetector detect(scx, obj);
327 if (!detect.init(cx))
330 if (!scx->sb.append('{'))
333 Value vec[3] = { NullValue(), NullValue(), NullValue() };
334 AutoArrayRooter tvr(cx, JS_ARRAY_LENGTH(vec), vec);
335 Value& outputValue = vec[0];
336 Value& whitelistElement = vec[1];
337 AutoIdRooter idr(cx);
338 jsid& id = *idr.addr();
340 Value *keySource = vp;
341 bool usingWhitelist = false;
343 // if the replacer is an array, we use the keys from it
344 if (scx->replacer && JS_IsArrayObject(cx, scx->replacer)) {
345 usingWhitelist = true;
346 vec[2].setObject(*scx->replacer);
350 JSBool memberWritten = JS_FALSE;
351 AutoIdVector props(cx);
352 if (!GetPropertyNames(cx, &keySource->toObject(), JSITER_OWNONLY, &props))
355 for (size_t i = 0, len = props.length(); i < len; i++) {
356 outputValue.setUndefined();
358 if (!usingWhitelist) {
359 if (!js_ValueToStringId(cx, IdToValue(props[i]), &id))
362 // skip non-index properties
364 if (!js_IdIsIndex(props[i], &index))
367 if (!scx->replacer->getProperty(cx, props[i], &whitelistElement))
370 if (!js_ValueToStringId(cx, whitelistElement, &id))
374 // We should have a string id by this point. Either from
375 // JS_Enumerate's id array, or by converting an element
377 JS_ASSERT(JSID_IS_ATOM(id));
379 if (!JS_GetPropertyById(cx, obj, id, Jsvalify(&outputValue)))
382 if (outputValue.isObjectOrNull() && !js_TryJSON(cx, &outputValue))
385 // call this here, so we don't write out keys if the replacer function
386 // wants to elide the value.
387 if (!CallReplacerFunction(cx, id, obj, scx, &outputValue))
390 JSType type = JS_TypeOfValue(cx, Jsvalify(outputValue));
392 // elide undefined values and functions and XML
393 if (outputValue.isUndefined() || type == JSTYPE_FUNCTION || type == JSTYPE_XML)
396 // output a comma unless this is the first member to write
397 if (memberWritten && !scx->sb.append(','))
399 memberWritten = JS_TRUE;
401 if (!WriteIndent(cx, scx, scx->depth))
404 // Be careful below, this string is weakly rooted
405 JSString *s = js_ValueToString(cx, IdToValue(id));
409 JS::Anchor<JSString *> anchor(s);
410 size_t length = s->length();
411 const jschar *chars = s->getChars(cx);
415 if (!write_string(cx, scx->sb, chars, length) ||
416 !scx->sb.append(':') ||
417 !(scx->gap.empty() || scx->sb.append(' ')) ||
418 !Str(cx, id, obj, scx, &outputValue, true)) {
423 if (memberWritten && !WriteIndent(cx, scx, scx->depth - 1))
426 return scx->sb.append('}');
430 JA(JSContext *cx, Value *vp, StringifyContext *scx)
432 JSObject *obj = &vp->toObject();
434 CycleDetector detect(scx, obj);
435 if (!detect.init(cx))
438 if (!scx->sb.append('['))
442 if (!js_GetLengthProperty(cx, obj, &length))
445 if (length != 0 && !WriteIndent(cx, scx, scx->depth))
448 AutoValueRooter outputValue(cx);
452 for (i = 0; i < length; i++) {
455 if (!obj->getProperty(cx, id, outputValue.addr()))
458 if (!Str(cx, id, obj, scx, outputValue.addr()))
461 if (outputValue.value().isUndefined()) {
462 if (!scx->sb.append("null"))
466 if (i < length - 1) {
467 if (!scx->sb.append(','))
469 if (!WriteIndent(cx, scx, scx->depth))
474 if (length != 0 && !WriteIndent(cx, scx, scx->depth - 1))
477 return scx->sb.append(']');
481 CallReplacerFunction(JSContext *cx, jsid id, JSObject *holder, StringifyContext *scx, Value *vp)
483 if (scx->replacer && scx->replacer->isCallable()) {
484 Value vec[2] = { IdToValue(id), *vp};
485 if (!JS_CallFunctionValue(cx, holder, OBJECT_TO_JSVAL(scx->replacer),
486 2, Jsvalify(vec), Jsvalify(vp))) {
495 Str(JSContext *cx, jsid id, JSObject *holder, StringifyContext *scx, Value *vp, bool callReplacer)
497 JS_CHECK_RECURSION(cx, return JS_FALSE);
499 if (vp->isObject() && !js_TryJSON(cx, vp))
502 if (callReplacer && !CallReplacerFunction(cx, id, holder, scx, vp))
505 // catches string and number objects with no toJSON
506 if (vp->isObject()) {
507 JSObject *obj = &vp->toObject();
508 Class *clasp = obj->getClass();
509 if (clasp == &js_StringClass || clasp == &js_NumberClass)
510 *vp = obj->getPrimitiveThis();
513 if (vp->isString()) {
514 JSString *str = vp->toString();
515 size_t length = str->length();
516 const jschar *chars = str->getChars(cx);
519 return write_string(cx, scx->sb, chars, length);
523 return scx->sb.append("null");
526 return vp->toBoolean() ? scx->sb.append("true") : scx->sb.append("false");
528 if (vp->isNumber()) {
529 if (vp->isDouble()) {
530 jsdouble d = vp->toDouble();
531 if (!JSDOUBLE_IS_FINITE(d))
532 return scx->sb.append("null");
536 if (!NumberValueToStringBuffer(cx, *vp, sb))
539 return scx->sb.append(sb.begin(), sb.length());
542 if (vp->isObject() && !IsFunctionObject(*vp) && !IsXML(*vp)) {
546 ok = (JS_IsArrayObject(cx, &vp->toObject()) ? JA : JO)(cx, vp, scx);
557 js_Stringify(JSContext *cx, Value *vp, JSObject *replacer, const Value &space,
560 StringifyContext scx(cx, sb, replacer);
561 if (!scx.initializeGap(cx, space) || !scx.initializeStack())
564 JSObject *obj = NewBuiltinClassInstance(cx, &js_ObjectClass);
568 AutoObjectRooter tvr(cx, obj);
569 if (!obj->defineProperty(cx, ATOM_TO_JSID(cx->runtime->atomState.emptyAtom),
570 *vp, NULL, NULL, JSPROP_ENUMERATE)) {
574 return Str(cx, ATOM_TO_JSID(cx->runtime->atomState.emptyAtom), obj, &scx, vp);
577 // helper to determine whether a character could be part of a number
578 static JSBool IsNumChar(jschar c)
580 return ((c <= '9' && c >= '0') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E');
583 static JSBool HandleDataString(JSContext *cx, JSONParser *jp);
584 static JSBool HandleDataKeyString(JSContext *cx, JSONParser *jp);
585 static JSBool HandleDataNumber(JSContext *cx, JSONParser *jp);
586 static JSBool HandleDataKeyword(JSContext *cx, JSONParser *jp);
587 static JSBool PopState(JSContext *cx, JSONParser *jp);
590 Walk(JSContext *cx, jsid id, JSObject *holder, const Value &reviver, Value *vp)
592 JS_CHECK_RECURSION(cx, return false);
594 if (!holder->getProperty(cx, id, vp))
599 if (vp->isObject() && !(obj = &vp->toObject())->isCallable()) {
600 AutoValueRooter propValue(cx);
604 if (!js_GetLengthProperty(cx, obj, &length))
607 for (jsuint i = 0; i < length; i++) {
609 if (!js_IndexToId(cx, i, &index))
612 if (!Walk(cx, index, obj, reviver, propValue.addr()))
615 if (!obj->defineProperty(cx, index, propValue.value(), NULL, NULL, JSPROP_ENUMERATE))
619 AutoIdVector props(cx);
620 if (!GetPropertyNames(cx, obj, JSITER_OWNONLY, &props))
623 for (size_t i = 0, len = props.length(); i < len; i++) {
624 jsid idName = props[i];
625 if (!Walk(cx, idName, obj, reviver, propValue.addr()))
627 if (propValue.value().isUndefined()) {
628 if (!js_DeleteProperty(cx, obj, idName, propValue.addr(), false))
631 if (!obj->defineProperty(cx, idName, propValue.value(), NULL, NULL,
640 // return reviver.call(holder, key, value);
641 const Value &value = *vp;
642 JSString *key = js_ValueToString(cx, IdToValue(id));
646 Value vec[2] = { StringValue(key), value };
648 if (!JS_CallFunctionValue(cx, holder, Jsvalify(reviver),
649 2, Jsvalify(vec), Jsvalify(&reviverResult))) {
658 JSONParseError(JSONParser *jp, JSContext *cx)
660 if (!jp->suppressErrors)
661 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_JSON_BAD_PARSE);
666 Revive(JSContext *cx, const Value &reviver, Value *vp)
669 JSObject *obj = NewBuiltinClassInstance(cx, &js_ObjectClass);
673 AutoObjectRooter tvr(cx, obj);
674 if (!obj->defineProperty(cx, ATOM_TO_JSID(cx->runtime->atomState.emptyAtom),
675 *vp, NULL, NULL, JSPROP_ENUMERATE)) {
679 return Walk(cx, ATOM_TO_JSID(cx->runtime->atomState.emptyAtom), obj, reviver, vp);
683 js_BeginJSONParse(JSContext *cx, Value *rootVal, bool suppressErrors /*= false*/)
688 JSObject *arr = NewDenseEmptyArray(cx);
692 JSONParser *jp = cx->create<JSONParser>(cx);
696 jp->objectStack = arr;
697 if (!JS_AddNamedObjectRoot(cx, &jp->objectStack, "JSON parse stack"))
700 jp->statep = jp->stateStack;
701 *jp->statep = JSON_PARSE_STATE_INIT;
702 jp->rootVal = rootVal;
703 jp->suppressErrors = suppressErrors;
708 js_FinishJSONParse(cx, jp, NullValue());
713 js_FinishJSONParse(JSContext *cx, JSONParser *jp, const Value &reviver)
718 JSBool early_ok = JS_TRUE;
720 // Check for unprocessed primitives at the root. This doesn't happen for
721 // strings because a closing quote triggers value processing.
722 if ((jp->statep - jp->stateStack) == 1) {
723 if (*jp->statep == JSON_PARSE_STATE_KEYWORD) {
724 early_ok = HandleDataKeyword(cx, jp);
727 } else if (*jp->statep == JSON_PARSE_STATE_NUMBER) {
728 early_ok = HandleDataNumber(cx, jp);
734 // This internal API is infallible, in spite of its JSBool return type.
735 js_RemoveRoot(cx->runtime, &jp->objectStack);
737 bool ok = *jp->statep == JSON_PARSE_STATE_FINISHED;
738 Value *vp = jp->rootVal;
743 JSONParseError(jp, cx);
744 } else if (reviver.isObject() && reviver.toObject().isCallable()) {
745 ok = Revive(cx, reviver, vp);
754 PushState(JSContext *cx, JSONParser *jp, JSONParserState state)
756 if (*jp->statep == JSON_PARSE_STATE_FINISHED) {
758 return JSONParseError(jp, cx);
762 if ((uint32)(jp->statep - jp->stateStack) >= JS_ARRAY_LENGTH(jp->stateStack)) {
764 return JSONParseError(jp, cx);
773 PopState(JSContext *cx, JSONParser *jp)
776 if (jp->statep < jp->stateStack) {
777 jp->statep = jp->stateStack;
778 return JSONParseError(jp, cx);
781 if (*jp->statep == JSON_PARSE_STATE_INIT)
782 *jp->statep = JSON_PARSE_STATE_FINISHED;
788 PushValue(JSContext *cx, JSONParser *jp, JSObject *parent, const Value &value)
791 if (parent->isArray()) {
793 ok = js_GetLengthProperty(cx, parent, &len);
796 if (!js_IndexToId(cx, len, &index))
798 ok = parent->defineProperty(cx, index, value, NULL, NULL, JSPROP_ENUMERATE);
801 ok = JS_DefineUCProperty(cx, parent, jp->objectKey.begin(),
802 jp->objectKey.length(), Jsvalify(value),
803 NULL, NULL, JSPROP_ENUMERATE);
804 jp->objectKey.clear();
811 PushObject(JSContext *cx, JSONParser *jp, JSObject *obj)
814 if (!js_GetLengthProperty(cx, jp->objectStack, &len))
816 if (len >= JSON_MAX_DEPTH)
817 return JSONParseError(jp, cx);
819 AutoObjectRooter tvr(cx, obj);
820 Value v = ObjectOrNullValue(obj);
822 // Check if this is the root object
825 // This property must be enumerable to keep the array dense
826 if (!jp->objectStack->defineProperty(cx, INT_TO_JSID(0), *jp->rootVal,
827 NULL, NULL, JSPROP_ENUMERATE)) {
834 if (!jp->objectStack->getProperty(cx, INT_TO_JSID(len - 1), &p))
837 JSObject *parent = &p.toObject();
838 if (!PushValue(cx, jp, parent, v))
841 // This property must be enumerable to keep the array dense
842 if (!jp->objectStack->defineProperty(cx, INT_TO_JSID(len), v,
843 NULL, NULL, JSPROP_ENUMERATE)) {
851 OpenObject(JSContext *cx, JSONParser *jp)
853 JSObject *obj = NewBuiltinClassInstance(cx, &js_ObjectClass);
857 return PushObject(cx, jp, obj);
861 OpenArray(JSContext *cx, JSONParser *jp)
863 // Add an array to an existing array or object
864 JSObject *arr = NewDenseEmptyArray(cx);
868 return PushObject(cx, jp, arr);
872 CloseObject(JSContext *cx, JSONParser *jp)
875 if (!js_GetLengthProperty(cx, jp->objectStack, &len))
877 if (!js_SetLengthProperty(cx, jp->objectStack, len - 1))
884 CloseArray(JSContext *cx, JSONParser *jp)
886 return CloseObject(cx, jp);
890 PushPrimitive(JSContext *cx, JSONParser *jp, const Value &value)
892 AutoValueRooter tvr(cx, value);
895 if (!js_GetLengthProperty(cx, jp->objectStack, &len))
900 if (!jp->objectStack->getProperty(cx, INT_TO_JSID(len - 1), &o))
903 return PushValue(cx, jp, &o.toObject(), value);
906 // root value must be primitive
907 *jp->rootVal = value;
912 HandleNumber(JSContext *cx, JSONParser *jp, const jschar *buf, uint32 len)
916 if (!js_strtod(cx, buf, buf + len, &ep, &val))
918 if (ep != buf + len) {
920 return JSONParseError(jp, cx);
923 return PushPrimitive(cx, jp, NumberValue(val));
927 HandleString(JSContext *cx, JSONParser *jp, const jschar *buf, uint32 len)
929 JSString *str = js_NewStringCopyN(cx, buf, len);
933 return PushPrimitive(cx, jp, StringValue(str));
937 HandleKeyword(JSContext *cx, JSONParser *jp, const jschar *buf, uint32 len)
939 const KeywordInfo *ki = FindKeyword(buf, len);
940 if (!ki || ki->tokentype != TOK_PRIMARY) {
942 return JSONParseError(jp, cx);
948 } else if (buf[0] == 't') {
949 keyword.setBoolean(true);
950 } else if (buf[0] == 'f') {
951 keyword.setBoolean(false);
953 return JSONParseError(jp, cx);
956 return PushPrimitive(cx, jp, keyword);
960 HandleDataString(JSContext *cx, JSONParser *jp)
962 JSBool ok = HandleString(cx, jp, jp->buffer.begin(), jp->buffer.length());
969 HandleDataKeyString(JSContext *cx, JSONParser *jp)
971 JSBool ok = jp->objectKey.append(jp->buffer.begin(), jp->buffer.end());
978 HandleDataNumber(JSContext *cx, JSONParser *jp)
980 JSBool ok = HandleNumber(cx, jp, jp->buffer.begin(), jp->buffer.length());
987 HandleDataKeyword(JSContext *cx, JSONParser *jp)
989 JSBool ok = HandleKeyword(cx, jp, jp->buffer.begin(), jp->buffer.length());
996 js_ConsumeJSONText(JSContext *cx, JSONParser *jp, const jschar *data, uint32 len,
997 DecodingMode decodingMode)
1001 if (*jp->statep == JSON_PARSE_STATE_INIT) {
1002 PushState(cx, jp, JSON_PARSE_STATE_VALUE);
1005 for (uint32 i = 0; i < len; i++) {
1007 switch (*jp->statep) {
1008 case JSON_PARSE_STATE_ARRAY_INITIAL_VALUE:
1010 if (!PopState(cx, jp))
1012 JS_ASSERT(*jp->statep == JSON_PARSE_STATE_ARRAY_AFTER_ELEMENT);
1013 if (!CloseArray(cx, jp) || !PopState(cx, jp))
1017 // fall through if non-empty array or whitespace
1019 case JSON_PARSE_STATE_VALUE:
1021 *jp->statep = JSON_PARSE_STATE_STRING;
1026 *jp->statep = JSON_PARSE_STATE_NUMBER;
1027 if (!jp->buffer.append(c))
1033 *jp->statep = JSON_PARSE_STATE_KEYWORD;
1034 if (!jp->buffer.append(c))
1040 *jp->statep = JSON_PARSE_STATE_OBJECT_AFTER_PAIR;
1041 if (!OpenObject(cx, jp) || !PushState(cx, jp, JSON_PARSE_STATE_OBJECT_INITIAL_PAIR))
1043 } else if (c == '[') {
1044 *jp->statep = JSON_PARSE_STATE_ARRAY_AFTER_ELEMENT;
1045 if (!OpenArray(cx, jp) || !PushState(cx, jp, JSON_PARSE_STATE_ARRAY_INITIAL_VALUE))
1047 } else if (JS_ISXMLSPACE(c)) {
1049 } else if (decodingMode == LEGACY && c == ']') {
1050 if (!PopState(cx, jp))
1052 JS_ASSERT(*jp->statep == JSON_PARSE_STATE_ARRAY_AFTER_ELEMENT);
1053 if (!CloseArray(cx, jp) || !PopState(cx, jp))
1056 return JSONParseError(jp, cx);
1060 case JSON_PARSE_STATE_ARRAY_AFTER_ELEMENT:
1062 if (!PushState(cx, jp, JSON_PARSE_STATE_VALUE))
1064 } else if (c == ']') {
1065 if (!CloseArray(cx, jp) || !PopState(cx, jp))
1067 } else if (!JS_ISXMLSPACE(c)) {
1068 return JSONParseError(jp, cx);
1072 case JSON_PARSE_STATE_OBJECT_AFTER_PAIR:
1074 if (!PushState(cx, jp, JSON_PARSE_STATE_OBJECT_PAIR))
1076 } else if (c == '}') {
1077 if (!CloseObject(cx, jp) || !PopState(cx, jp))
1079 } else if (!JS_ISXMLSPACE(c)) {
1080 return JSONParseError(jp, cx);
1084 case JSON_PARSE_STATE_OBJECT_INITIAL_PAIR:
1086 if (!PopState(cx, jp))
1088 JS_ASSERT(*jp->statep == JSON_PARSE_STATE_OBJECT_AFTER_PAIR);
1089 if (!CloseObject(cx, jp) || !PopState(cx, jp))
1093 // fall through if non-empty object or whitespace
1095 case JSON_PARSE_STATE_OBJECT_PAIR:
1097 // we want to be waiting for a : when the string has been read
1098 *jp->statep = JSON_PARSE_STATE_OBJECT_IN_PAIR;
1099 if (!PushState(cx, jp, JSON_PARSE_STATE_STRING))
1101 } else if (JS_ISXMLSPACE(c)) {
1103 } else if (decodingMode == LEGACY && c == '}') {
1104 if (!PopState(cx, jp))
1106 JS_ASSERT(*jp->statep == JSON_PARSE_STATE_OBJECT_AFTER_PAIR);
1107 if (!CloseObject(cx, jp) || !PopState(cx, jp))
1110 return JSONParseError(jp, cx);
1114 case JSON_PARSE_STATE_OBJECT_IN_PAIR:
1116 *jp->statep = JSON_PARSE_STATE_VALUE;
1117 } else if (!JS_ISXMLSPACE(c)) {
1118 return JSONParseError(jp, cx);
1122 case JSON_PARSE_STATE_STRING:
1124 if (!PopState(cx, jp))
1126 if (*jp->statep == JSON_PARSE_STATE_OBJECT_IN_PAIR) {
1127 if (!HandleDataKeyString(cx, jp))
1130 if (!HandleDataString(cx, jp))
1133 } else if (c == '\\') {
1134 *jp->statep = JSON_PARSE_STATE_STRING_ESCAPE;
1135 } else if (c <= 0x1F) {
1136 // The JSON lexical grammer does not allow a JSONStringCharacter to be
1137 // any of the Unicode characters U+0000 thru U+001F (control characters).
1138 return JSONParseError(jp, cx);
1140 if (!jp->buffer.append(c))
1145 case JSON_PARSE_STATE_STRING_ESCAPE:
1151 case 'b' : c = '\b'; break;
1152 case 'f' : c = '\f'; break;
1153 case 'n' : c = '\n'; break;
1154 case 'r' : c = '\r'; break;
1155 case 't' : c = '\t'; break;
1160 *jp->statep = JSON_PARSE_STATE_STRING_HEX;
1163 return JSONParseError(jp, cx);
1167 if (!jp->buffer.append(c))
1169 *jp->statep = JSON_PARSE_STATE_STRING;
1172 case JSON_PARSE_STATE_STRING_HEX:
1173 if (('0' <= c) && (c <= '9')) {
1174 jp->hexChar = (jp->hexChar << 4) | (c - '0');
1175 } else if (('a' <= c) && (c <= 'f')) {
1176 jp->hexChar = (jp->hexChar << 4) | (c - 'a' + 0x0a);
1177 } else if (('A' <= c) && (c <= 'F')) {
1178 jp->hexChar = (jp->hexChar << 4) | (c - 'A' + 0x0a);
1180 return JSONParseError(jp, cx);
1183 if (++(jp->numHex) == 4) {
1184 if (!jp->buffer.append(jp->hexChar))
1188 *jp->statep = JSON_PARSE_STATE_STRING;
1192 case JSON_PARSE_STATE_KEYWORD:
1194 if (!jp->buffer.append(c))
1197 // this character isn't part of the keyword, process it again
1199 if (!PopState(cx, jp))
1202 if (!HandleDataKeyword(cx, jp))
1207 case JSON_PARSE_STATE_NUMBER:
1209 if (!jp->buffer.append(c))
1212 // this character isn't part of the number, process it again
1214 if (!PopState(cx, jp))
1216 if (!HandleDataNumber(cx, jp))
1221 case JSON_PARSE_STATE_FINISHED:
1222 if (!JS_ISXMLSPACE(c)) {
1224 return JSONParseError(jp, cx);
1229 JS_NOT_REACHED("Invalid JSON parser state");
1238 json_toSource(JSContext *cx, uintN argc, Value *vp)
1240 vp->setString(ATOM_TO_STRING(CLASS_ATOM(cx, JSON)));
1245 static JSFunctionSpec json_static_methods[] = {
1247 JS_FN(js_toSource_str, json_toSource, 0, 0),
1249 JS_FN("parse", js_json_parse, 2, 0),
1250 JS_FN("stringify", js_json_stringify, 3, 0),
1255 js_InitJSONClass(JSContext *cx, JSObject *obj)
1259 JSON = NewNonFunction<WithProto::Class>(cx, &js_JSONClass, NULL, obj);
1262 if (!JS_DefineProperty(cx, obj, js_JSON_str, OBJECT_TO_JSVAL(JSON),
1263 JS_PropertyStub, JS_StrictPropertyStub, 0))
1266 if (!JS_DefineFunctions(cx, JSON, json_static_methods))