From 4d47dac2b1f64ad11e2051f324f43f9652d94117 Mon Sep 17 00:00:00 2001 From: Rafal Kupiec Date: Sun, 22 Nov 2026 14:53:55 +0100 Subject: [PATCH] Rewrite JSON module as typed object-oriented DOM --- modules/json/json.c | 3953 +++++++++++++++++++++++++++++++------------ modules/json/json.h | 131 +- 2 files changed, 2913 insertions(+), 1171 deletions(-) diff --git a/modules/json/json.c b/modules/json/json.c index b203936..47b02e3 100644 --- a/modules/json/json.c +++ b/modules/json/json.c @@ -2,217 +2,754 @@ * @PROJECT AerScript Interpreter * @COPYRIGHT See COPYING in the top level directory * @FILE modules/json/json.c - * @DESCRIPTION JavaScript Object Notation (JSON) module for AerScript Interpreter + * @DESCRIPTION Typed JSON DOM module for AerScript Interpreter * @DEVELOPERS Symisc Systems * Rafal Kupiec */ #include #include +#include #include "json.h" #ifdef __WINNT__ #include #endif -/* - * JSON_HEX_TAG. - * Expand the value of JSON_HEX_TAG defined in ph7Int.h. - */ -static void PH7_JSON_HEX_TAG_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_HEX_TAG); -} -/* - * JSON_HEX_AMP. - * Expand the value of JSON_HEX_AMP defined in ph7Int.h. - */ -static void PH7_JSON_HEX_AMP_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_HEX_AMP); -} -/* - * JSON_HEX_APOS. - * Expand the value of JSON_HEX_APOS defined in ph7Int.h. - */ -static void PH7_JSON_HEX_APOS_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_HEX_APOS); -} -/* - * JSON_HEX_QUOT. - * Expand the value of JSON_HEX_QUOT defined in ph7Int.h. - */ -static void PH7_JSON_HEX_QUOT_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_HEX_QUOT); -} -/* - * JSON_FORCE_OBJECT. - * Expand the value of JSON_FORCE_OBJECT defined in ph7Int.h. - */ -static void PH7_JSON_FORCE_OBJECT_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_FORCE_OBJECT); -} -/* - * JSON_NUMERIC_CHECK. - * Expand the value of JSON_NUMERIC_CHECK defined in ph7Int.h. - */ -static void PH7_JSON_NUMERIC_CHECK_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_NUMERIC_CHECK); -} -/* - * JSON_BIGINT_AS_STRING. - * Expand the value of JSON_BIGINT_AS_STRING defined in ph7Int.h. - */ -static void PH7_JSON_BIGINT_AS_STRING_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_BIGINT_AS_STRING); -} -/* - * JSON_PRETTY_PRINT. - * Expand the value of JSON_PRETTY_PRINT defined in ph7Int.h. - */ -static void PH7_JSON_PRETTY_PRINT_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_PRETTY_PRINT); -} -/* - * JSON_UNESCAPED_SLASHES. - * Expand the value of JSON_UNESCAPED_SLASHES defined in ph7Int.h. - */ -static void PH7_JSON_UNESCAPED_SLASHES_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_UNESCAPED_SLASHES); -} -/* - * JSON_UNESCAPED_UNICODE. - * Expand the value of JSON_UNESCAPED_UNICODE defined in ph7Int.h. - */ -static void PH7_JSON_UNESCAPED_UNICODE_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_UNESCAPED_UNICODE); -} -/* - * JSON_ERROR_NONE. - * Expand the value of JSON_ERROR_NONE defined in ph7Int.h. - */ -static void PH7_JSON_ERROR_NONE_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_ERROR_NONE); -} -/* - * JSON_ERROR_DEPTH. - * Expand the value of JSON_ERROR_DEPTH defined in ph7Int.h. - */ -static void PH7_JSON_ERROR_DEPTH_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_ERROR_DEPTH); -} -/* - * JSON_ERROR_STATE_MISMATCH. - * Expand the value of JSON_ERROR_STATE_MISMATCH defined in ph7Int.h. - */ -static void PH7_JSON_ERROR_STATE_MISMATCH_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_ERROR_STATE_MISMATCH); -} -/* - * JSON_ERROR_CTRL_CHAR. - * Expand the value of JSON_ERROR_CTRL_CHAR defined in ph7Int.h. - */ -static void PH7_JSON_ERROR_CTRL_CHAR_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_ERROR_CTRL_CHAR); -} -/* - * JSON_ERROR_SYNTAX. - * Expand the value of JSON_ERROR_SYNTAX defined in ph7Int.h. - */ -static void PH7_JSON_ERROR_SYNTAX_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_ERROR_SYNTAX); -} -/* - * JSON_ERROR_UTF8. - * Expand the value of JSON_ERROR_UTF8 defined in ph7Int.h. - */ -static void PH7_JSON_ERROR_UTF8_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, JSON_ERROR_UTF8); -} -/* - * Default container nesting depth, also used as the json_encode() limit. - */ -#define JSON_MAX_DEPTH 32 -/* - * Hard limit for the json_decode() recursion depth. A larger $depth argument - * is rejected with JSON_ERROR_DEPTH before any parsing takes place, because - * the decoder is recursive and must not be allowed to exhaust the C stack. - */ -#define JSON_MAX_DECODE_DEPTH 512 +/* Class names used by the DOM. */ +#define JCLS_EXC "JsonException" +#define JCLS_NODE "JsonNode" +#define JCLS_OBJECT "JsonObjectNode" +#define JCLS_ARRAY "JsonArrayNode" +#define JCLS_STRING "JsonStringNode" +#define JCLS_NUMBER "JsonNumberNode" +#define JCLS_BOOL "JsonBooleanNode" +#define JCLS_NULL "JsonNullNode" +#define JCLS_DOC "JsonDocument" +#define JCLS_FACADE "Json" +#define JCLS_OPTIONS "JsonOptions" +#define JCLS_KIND "JsonNodeType" -/* - * Append a JSON string literal to the current call result. - * Double quotes and backslashes are always escaped, control characters are - * encoded according to the JSON grammar and the JSON_HEX_* options are honored. - * The input is processed by length, so it may contain embedded NUL bytes. - */ -static void VmJsonAppendString(ph7_context *pCtx, const char *zIn, sxu32 nByte, sxi32 iFlags) { - char zEscape[8]; - sxu32 i; - sxi32 c; - /* Append the opening double quote */ - ph7_result_string(pCtx, "\"", (int)sizeof(char)); - for(i = 0; i < nByte; i++) { - c = (unsigned char)zIn[i]; - if(c == '<' && (iFlags & JSON_HEX_TAG)) { - ph7_result_string(pCtx, "\\u003C", (int)sizeof("\\u003C") - 1); - } else if(c == '>' && (iFlags & JSON_HEX_TAG)) { - ph7_result_string(pCtx, "\\u003E", (int)sizeof("\\u003E") - 1); - } else if(c == '&' && (iFlags & JSON_HEX_AMP)) { - ph7_result_string(pCtx, "\\u0026", (int)sizeof("\\u0026") - 1); - } else if(c == '\'' && (iFlags & JSON_HEX_APOS)) { - ph7_result_string(pCtx, "\\u0027", (int)sizeof("\\u0027") - 1); - } else if(c == '"' && (iFlags & JSON_HEX_QUOT)) { - ph7_result_string(pCtx, "\\u0022", (int)sizeof("\\u0022") - 1); - } else if(c == '"') { - ph7_result_string(pCtx, "\\\"", (int)sizeof("\\\"") - 1); - } else if(c == '\\') { - ph7_result_string(pCtx, "\\\\", (int)sizeof("\\\\") - 1); - } else if(c == '/') { - if(iFlags & JSON_UNESCAPED_SLASHES) { - ph7_result_string(pCtx, "/", (int)sizeof(char)); - } else { - ph7_result_string(pCtx, "\\/", (int)sizeof("\\/") - 1); +#define JSON_DEFAULT_MAX_DEPTH 512 + +/* Native type shorthands. */ +#define JTY(T) { PH7_TYPE_##T, 0, 0 } +#define JTYARR(T) { PH7_TYPE_##T, 0, 1 } +#define JNM(N) { PH7_TYPE_NAMED, N, 0 } +#define JAR(N) { PH7_TYPE_NAMED, N, 1 } +#define JP(N,T) { N, JTY(T), 0, 0, 0, 0 } +#define JPN(N,X) { N, X, 0, 0, 0, 0 } +#define JPO(N,X,D) { N, X, 0, D, 0, 0 } + +/* ------------------------------------------------------------------ */ +/* Direct field access */ +/* ------------------------------------------------------------------ */ + +/* Return the live slot of an instance attribute without a scope check. + * DOM helpers run from callbacks declared in several different classes; + * they all need to reach JsonNode's private fields. */ +static ph7_value *JsonField(ph7_value *pObj, const char *zName) { + ph7_class_instance *pInst; + SyString s; + if(pObj == 0 || (pObj->nType & MEMOBJ_OBJ) == 0 || pObj->x.pOther == 0) { + return 0; + } + pInst = (ph7_class_instance *)pObj->x.pOther; + SyStringInitFromBuf(&s, zName, (sxu32)SyStrlen(zName)); + return PH7_ClassInstanceFetchAttr(pInst, &s); +} +static ph7_int64 JsonFieldInt(ph7_value *pObj, const char *zName) { + ph7_value *p = JsonField(pObj, zName); + return p ? ph7_value_to_int64(p) : 0; +} +static int JsonFieldBool(ph7_value *pObj, const char *zName) { + ph7_value *p = JsonField(pObj, zName); + return p ? ph7_value_to_bool(p) : 0; +} +static const char *JsonFieldStr(ph7_value *pObj, const char *zName, int *pLen) { + ph7_value *p = JsonField(pObj, zName); + if(p == 0) { + if(pLen) *pLen = 0; + return ""; + } + return ph7_value_to_string(p, pLen); +} +static double JsonFieldDouble(ph7_value *pObj, const char *zName) { + ph7_value *p = JsonField(pObj, zName); + return p ? ph7_value_to_double(p) : 0.0; +} +static int JsonFieldSetInt(ph7_value *pObj, const char *zName, ph7_int64 iVal) { + ph7_value *p = JsonField(pObj, zName); + return p ? ph7_value_int64(p, iVal) : PH7_CORRUPT; +} +static int JsonFieldSetBool(ph7_value *pObj, const char *zName, int bVal) { + ph7_value *p = JsonField(pObj, zName); + return p ? ph7_value_bool(p, bVal) : PH7_CORRUPT; +} +static int JsonFieldSetDouble(ph7_value *pObj, const char *zName, double rVal) { + ph7_value *p = JsonField(pObj, zName); + return p ? ph7_value_double(p, rVal) : PH7_CORRUPT; +} +static int JsonFieldSetStr(ph7_value *pObj, const char *zName, const char *zVal, int nByte) { + ph7_value *p = JsonField(pObj, zName); + char *zCopy; + sxi32 rc; + if(p == 0) { + return PH7_CORRUPT; + } + if(zVal == 0) { + zVal = ""; + nByte = 0; + } + if(nByte < 0) { + nByte = (int)SyStrlen(zVal); + } + /* ph7_value_string() appends to an existing string blob, and callers such + * as JsonRepath() pass a pointer into the very field being replaced. Copy + * the source before releasing the destination. */ + zCopy = (char *)SyMemBackendAlloc(&pObj->pVm->sAllocator, (sxu32)nByte + 1); + if(zCopy == 0) { + return PH7_NOMEM; + } + memcpy(zCopy, zVal, (sxu32)nByte); + zCopy[nByte] = '\0'; + PH7_MemObjRelease(p); + PH7_MemObjInit(pObj->pVm, p); + rc = ph7_value_string(p, zCopy, nByte); + SyMemBackendFree(&pObj->pVm->sAllocator, zCopy); + return rc; +} +/* Replace a container/object slot with a snapshot of the source value. + * Snapshot reserves arena members, so reacquire the destination slot before + * writing the owned copy back. */ +static int JsonFieldSetObj(ph7_value *pObj, const char *zName, ph7_value *pSrc) { + ph7_value *p = JsonField(pObj, zName); + ph7_value sTmp; + sxi32 rc; + if(p == 0 || pSrc == 0) { + return PH7_CORRUPT; + } + PH7_MemObjInit(pObj->pVm, &sTmp); + rc = PH7_MemObjSnapshot(pSrc, &sTmp); + if(rc != SXRET_OK) { + PH7_MemObjRelease(&sTmp); + return rc; + } + p = JsonField(pObj, zName); + if(p == 0) { + PH7_MemObjRelease(&sTmp); + return PH7_CORRUPT; + } + PH7_MemObjRelease(p); + PH7_MemObjInit(pObj->pVm, p); + rc = PH7_MemObjStore(&sTmp, p); + PH7_MemObjRelease(&sTmp); + return rc; +} +static ph7_value *JsonFieldContainer(ph7_value *pObj, const char *zName) { + ph7_value *p = JsonField(pObj, zName); + return (p && (p->nType & MEMOBJ_HASHMAP)) ? p : 0; +} + +/* ------------------------------------------------------------------ */ +/* JsonException support */ +/* ------------------------------------------------------------------ */ +static const char *JsonErrorDescription(int nErr) { + switch(nErr) { + case JSON_ERROR_NONE: return "No error"; + case JSON_ERROR_DEPTH: return "Maximum depth exceeded"; + case JSON_ERROR_STATE_MISMATCH: return "State mismatch"; + case JSON_ERROR_CTRL_CHAR: return "Control character error"; + case JSON_ERROR_SYNTAX: return "Syntax error"; + case JSON_ERROR_UTF8: return "Invalid UTF-8"; + case JSON_ERROR_TYPE_MISMATCH: return "Type mismatch"; + case JSON_ERROR_KEY_NOT_FOUND: return "Key not found"; + case JSON_ERROR_INDEX_OUT_OF_RANGE: return "Index out of range"; + case JSON_ERROR_DUPLICATE_KEY: return "Duplicate key"; + case JSON_ERROR_INVALID_OPERATION: return "Invalid operation"; + case JSON_ERROR_INVALID_OPTION: return "Invalid option"; + case JSON_ERROR_READONLY_OPTION: return "Options are read-only"; + default: return "Unknown error code"; + } +} +/* Fetch an inherited (protected) attribute slot straight off the instance. + * PH7_ClassInstanceFetchAttr walks the attribute table without a scope check, + * so the base Exception fields are reachable from this module. */ +static ph7_value *JsonInstField(ph7_class_instance *pInst, const char *zName) { + SyString s; + if(pInst == 0) { + return 0; + } + SyStringInitFromBuf(&s, zName, (sxu32)SyStrlen(zName)); + return PH7_ClassInstanceFetchAttr(pInst, &s); +} +/* Stamp the inherited Exception file/line fields with the first script frame + * of the active call stack. Native frames ([NATIVE], line 0) are skipped so + * catch(Exception $e) observes the place in the script that raised the error. */ +static void JsonStampSite(ph7_vm *pVm, ph7_class_instance *pInst) { + SySet sTrace; + VmDebugTrace *pTrace; + ph7_value *pField; + if(VmExtractDebugTrace(pVm, &sTrace) != SXRET_OK) { + return; + } + while(SySetGetNextEntry(&sTrace, (void **)&pTrace) == SXRET_OK) { + if(pTrace->pFile == 0 || pTrace->nLine == 0) { + continue; + } + if(pTrace->pFile->nByte == sizeof("[NATIVE]") - 1 && + SyMemcmp(pTrace->pFile->zString, "[NATIVE]", sizeof("[NATIVE]") - 1) == 0) { + continue; + } + pField = JsonInstField(pInst, "file"); + if(pField) { + PH7_MemObjRelease(pField); + PH7_MemObjInit(pVm, pField); + (void)ph7_value_string(pField, pTrace->pFile->zString, (int)pTrace->pFile->nByte); + } + pField = JsonInstField(pInst, "line"); + if(pField) { + (void)ph7_value_int64(pField, (ph7_int64)pTrace->nLine); + } + break; + } + SySetRelease(&sTrace); +} +/* Throw a real JsonException object; input line/column/path are carried verbatim. */ +static int JsonThrow(ph7_context *pCtx, int nErr, const char *zMsg, + sxu32 nLine, sxu32 nCol, const char *zPath) { + ph7_vm *pVm = pCtx->pVm; + ph7_class *pClass; + ph7_class_instance *pInst; + ph7_class_method *pCons; + ph7_value *pObj, *apArg[5], *aTmp[5]; + sxi32 rc; + sxu32 n; + if(pVm->iPendingTransfer) { + return PH7_EXCEPTION; + } + pClass = PH7_VmExtractClass(pVm, JCLS_EXC, sizeof(JCLS_EXC) - 1, FALSE); + if(pClass == 0) { + return PH7_ABORT; + } + pInst = PH7_NewClassInstance(pVm, pClass); + if(pInst == 0) { + PH7_VmMemoryError(pVm); + return PH7_ABORT; + } + for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) { + aTmp[n] = ph7_context_new_scalar(pCtx); + if(aTmp[n] == 0) { + while(n > 0) { + --n; + ph7_context_release_value(pCtx, aTmp[n]); } - } else if(c == '\b') { - ph7_result_string(pCtx, "\\b", (int)sizeof("\\b") - 1); - } else if(c == '\f') { - ph7_result_string(pCtx, "\\f", (int)sizeof("\\f") - 1); - } else if(c == '\n') { - ph7_result_string(pCtx, "\\n", (int)sizeof("\\n") - 1); - } else if(c == '\r') { - ph7_result_string(pCtx, "\\r", (int)sizeof("\\r") - 1); - } else if(c == '\t') { - ph7_result_string(pCtx, "\\t", (int)sizeof("\\t") - 1); - } else if(c < 0x20) { - snprintf(zEscape, sizeof(zEscape), "\\u%04X", c); - ph7_result_string(pCtx, zEscape, (int)SyStrlen(zEscape)); - } else { - ph7_result_string(pCtx, &zIn[i], (int)sizeof(char)); + PH7_ClassInstanceUnref(pInst); + PH7_VmMemoryError(pVm); + return PH7_ABORT; } } - /* Append the closing double quote */ - ph7_result_string(pCtx, "\"", (int)sizeof(char)); + pObj = ph7_context_new_scalar(pCtx); + if(pObj == 0) { + for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) { + ph7_context_release_value(pCtx, aTmp[n]); + } + PH7_ClassInstanceUnref(pInst); + PH7_VmMemoryError(pVm); + return PH7_ABORT; + } + ph7_value_string(aTmp[0], zMsg, -1); + ph7_value_int64(aTmp[1], nErr); + ph7_value_int64(aTmp[2], (ph7_int64)nLine); + ph7_value_int64(aTmp[3], (ph7_int64)nCol); + ph7_value_string(aTmp[4], zPath, -1); + for(n = 0 ; n < SX_ARRAYSIZE(apArg) ; ++n) { + apArg[n] = aTmp[n]; + } + pCons = PH7_ClassExtractMethod(pClass, "__construct", sizeof("__construct") - 1); + if(pCons) { + rc = PH7_VmCallClassMethod(pVm, pInst, pCons, 0, 5, apArg); + if(pInst->iRef < 1) { + pInst->iRef = 1; + } + for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) { + ph7_context_release_value(pCtx, aTmp[n]); + } + if(rc != PH7_OK) { + ph7_context_release_value(pCtx, pObj); + PH7_ClassInstanceUnref(pInst); + return rc; + } + } else { + for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) { + ph7_context_release_value(pCtx, aTmp[n]); + } + } + /* Base Exception fields describe the throwing script, not the JSON input. */ + JsonStampSite(pVm, pInst); + if(pInst->iRef < 1) { + pInst->iRef = 1; + } + PH7_MemObjRelease(pObj); + pObj->x.pOther = pInst; + MemObjSetType(pObj, MEMOBJ_OBJ); + rc = ph7_result_value(pCtx, pObj); + ph7_context_release_value(pCtx, pObj); + return rc == PH7_OK ? PH7_EXCEPTION : rc; } -/* - * Format a real number using the shortest representation that parses back - * to the exact same double. - */ -static sxi32 VmJsonFormatReal(char *zBuf, sxu32 nBufSize, ph7_real rVal) { +static int JsonThrowOption(ph7_context *pCtx, int nErr, const char *zMsg) { + return JsonThrow(pCtx, nErr, zMsg, 0, 0, ""); +} +static int JsonThrowFmt(ph7_context *pCtx, int nErr, const char *zFmt, int iVal) { + char zBuf[256]; + SyBufferFormat(zBuf, sizeof(zBuf), zFmt, iVal); + return JsonThrowOption(pCtx, nErr, zBuf); +} + +/* ------------------------------------------------------------------ */ +/* JsonOptions configuration */ +/* ------------------------------------------------------------------ */ +typedef struct json_opt json_opt; +struct json_opt { + int prettyPrint; + int unescapedUnicode; + int unescapedSlashes; + int hexTag; + int hexAmp; + int hexApos; + int hexQuot; + int numericCheck; + int bigintAsString; + int allowComments; + int allowTrailingComma; + int duplicateKeyPolicy; + int maxDepth; + char indent[64]; + int indentLen; +}; +static void JsonOptDefaults(json_opt *p) { + SyZero(p, sizeof(*p)); + p->duplicateKeyPolicy = JSON_DUP_KEEP_LAST; + p->maxDepth = JSON_DEFAULT_MAX_DEPTH; + memcpy(p->indent, " ", 2); + p->indent[2] = '\0'; + p->indentLen = 2; +} +/* Validate an options instance. This is a pure test: it never mutates the + * instance. All diagnostics use the exact option-message wording and carry + * input line=0, input column=0, path="". */ +static int JsonOptValidate(ph7_context *pCtx, ph7_value *pOptions) { + int nMax, nPolicy, nByte, i; + const char *zIndent; + if(pOptions == 0 || !ph7_value_is_object(pOptions)) { + return PH7_CORRUPT; + } + nMax = (int)JsonFieldInt(pOptions, "maxDepth"); + if(nMax < 1 || nMax > JSON_DEFAULT_MAX_DEPTH) { + return JsonThrowFmt(pCtx, JSON_ERROR_INVALID_OPTION, + "JsonOptions.MaxDepth must be in range 1..512 (got %d)", nMax); + } + nPolicy = (int)JsonFieldInt(pOptions, "duplicateKeyPolicy"); + if(nPolicy != JSON_DUP_KEEP_LAST && nPolicy != JSON_DUP_KEEP_FIRST && nPolicy != JSON_DUP_REJECT) { + return JsonThrowFmt(pCtx, JSON_ERROR_INVALID_OPTION, + "JsonOptions.DuplicateKeyPolicy must be JsonOptions.KEEP_LAST, KEEP_FIRST or REJECT (got %d)", + nPolicy); + } + zIndent = JsonFieldStr(pOptions, "indent", &nByte); + if(nByte > 32) { + return JsonThrowOption(pCtx, JSON_ERROR_INVALID_OPTION, + "JsonOptions.Indent may contain only spaces/tabs and must be at most 32 bytes"); + } + for(i = 0 ; i < nByte ; ++i) { + if(zIndent[i] != ' ' && zIndent[i] != '\t') { + return JsonThrowOption(pCtx, JSON_ERROR_INVALID_OPTION, + "JsonOptions.Indent may contain only spaces/tabs and must be at most 32 bytes"); + } + } + return PH7_OK; +} +/* Validate, mark read-only on first use, then copy the scalar option values + * out of the instance. */ +static int JsonOptLoad(ph7_context *pCtx, ph7_value *pOptions, json_opt *pOut) { + int nByte; + const char *zIndent; + int rc; + /* Explicit null means "use the defaults": a bare null, or a JsonOptions- + * typed null, which the VM represents as an object type with no instance. + * JsonOptValidate itself stays strict for the public Validate() method. */ + if(pOptions == 0 || (pOptions->nType & MEMOBJ_NULL) || + !ph7_value_is_object(pOptions) || pOptions->x.pOther == 0) { + JsonOptDefaults(pOut); + return PH7_OK; + } + rc = JsonOptValidate(pCtx, pOptions); + if(rc != PH7_OK) { + return rc; + } + /* First consuming call seals the instance: later setters are rejected. */ + (void)JsonFieldSetBool(pOptions, "readOnly", 1); + JsonOptDefaults(pOut); + pOut->prettyPrint = JsonFieldBool(pOptions, "prettyPrint"); + pOut->unescapedUnicode = JsonFieldBool(pOptions, "unescapedUnicode"); + pOut->unescapedSlashes = JsonFieldBool(pOptions, "unescapedSlashes"); + pOut->hexTag = JsonFieldBool(pOptions, "hexTag"); + pOut->hexAmp = JsonFieldBool(pOptions, "hexAmp"); + pOut->hexApos = JsonFieldBool(pOptions, "hexApos"); + pOut->hexQuot = JsonFieldBool(pOptions, "hexQuot"); + pOut->numericCheck = JsonFieldBool(pOptions, "numericCheck"); + pOut->bigintAsString = JsonFieldBool(pOptions, "bigintAsString"); + pOut->allowComments = JsonFieldBool(pOptions, "allowComments"); + pOut->allowTrailingComma = JsonFieldBool(pOptions, "allowTrailingComma"); + pOut->duplicateKeyPolicy = (int)JsonFieldInt(pOptions, "duplicateKeyPolicy"); + pOut->maxDepth = (int)JsonFieldInt(pOptions, "maxDepth"); + zIndent = JsonFieldStr(pOptions, "indent", &nByte); + if(nByte > (int)sizeof(pOut->indent) - 1) { + nByte = (int)sizeof(pOut->indent) - 1; + } + memcpy(pOut->indent, zIndent, (sxu32)nByte); + pOut->indent[nByte] = '\0'; + pOut->indentLen = nByte; + return PH7_OK; +} + +/* ------------------------------------------------------------------ */ +/* Node construction and path helpers */ +/* ------------------------------------------------------------------ */ +static ph7_value *JsonNewNode(ph7_context *pCtx, const char *zClass, int nKind, const char *zPath) { + ph7_vm *pVm = pCtx->pVm; + ph7_class *pClass = PH7_VmExtractClass(pVm, zClass, (sxu32)SyStrlen(zClass), FALSE); + ph7_class_instance *pInst; + ph7_value *pObj, *pArray; + if(pClass == 0) { + return 0; + } + pObj = ph7_context_new_scalar(pCtx); + if(pObj == 0) { + return 0; + } + pInst = PH7_NewClassInstance(pVm, pClass); + if(pInst == 0) { + ph7_context_release_value(pCtx, pObj); + PH7_VmMemoryError(pVm); + return 0; + } + if(pInst->iRef < 1) { + pInst->iRef = 1; + } + PH7_MemObjRelease(pObj); + pObj->x.pOther = pInst; + MemObjSetType(pObj, MEMOBJ_OBJ); + JsonFieldSetInt(pObj, "kind", nKind); + JsonFieldSetStr(pObj, "path", zPath, -1); + JsonFieldSetInt(pObj, "depth", 0); + JsonFieldSetStr(pObj, "text", "", 0); + JsonFieldSetInt(pObj, "intValue", 0); + JsonFieldSetDouble(pObj, "realValue", 0.0); + JsonFieldSetBool(pObj, "boolValue", 0); + JsonFieldSetStr(pObj, "rawNumber", "", 0); + pArray = ph7_context_new_array(pCtx); + if(pArray == 0 || JsonFieldSetObj(pObj, "children", pArray) != PH7_OK) { + ph7_context_release_value(pCtx, pObj); + if(pArray) ph7_context_release_value(pCtx, pArray); + PH7_VmMemoryError(pVm); + return 0; + } + ph7_context_release_value(pCtx, pArray); + return pObj; +} +/* Recompute eager paths and depths for a node and its whole subtree. + * The shared blob holds pNode's own path on entry. Each level appends a child + * suffix and truncates the blob back on return, so no path byte limit and no + * per-level path buffer are needed. */ +static int JsonRepath(ph7_context *pCtx, SyBlob *pPath, ph7_value *pNode, int nDepth); +static sxi32 JsonBlobAppendInt(SyBlob *pBlob, int n) { + char zNum[32]; + SyBufferFormat(zNum, sizeof(zNum), "%d", n); + return SyBlobAppend(pBlob, zNum, (sxu32)SyStrlen(zNum)); +} +struct JsonRepathWalk { + ph7_context *pCtx; + SyBlob *pPath; + int nKind; + int nIndex; + int nDepth; + int rc; +}; +static int JsonRepathWalker(ph7_value *pKey, ph7_value *pValue, void *pUserData) { + struct JsonRepathWalk *pWalk = (struct JsonRepathWalk *)pUserData; + sxu32 nMark = SyBlobLength(pWalk->pPath); + sxi32 rc; + if(pValue == 0 || (pValue->nType & MEMOBJ_OBJ) == 0 || pValue->x.pOther == 0) { + return 0; + } + if(pWalk->nKind == JSON_NODE_OBJECT) { + int nKey = 0; + const char *zKey = pKey ? ph7_value_to_string(pKey, &nKey) : ""; + rc = SyBlobAppend(pWalk->pPath, ".", 1); + if(rc == SXRET_OK) { + rc = SyBlobAppend(pWalk->pPath, zKey ? zKey : "", (sxu32)nKey); + } + } else { + rc = SyBlobAppend(pWalk->pPath, "[", 1); + if(rc == SXRET_OK) { + rc = JsonBlobAppendInt(pWalk->pPath, pWalk->nIndex); + } + if(rc == SXRET_OK) { + rc = SyBlobAppend(pWalk->pPath, "]", 1); + } + } + if(rc != SXRET_OK) { + SyBlobLength(pWalk->pPath) = nMark; + pWalk->rc = PH7_ABORT; + return 1; + } + ++pWalk->nIndex; + pWalk->rc = JsonRepath(pWalk->pCtx, pWalk->pPath, pValue, pWalk->nDepth + 1); + SyBlobLength(pWalk->pPath) = nMark; + return pWalk->rc == PH7_OK ? 0 : 1; +} +static int JsonRepath(ph7_context *pCtx, SyBlob *pPath, ph7_value *pNode, int nDepth) { + ph7_value *pChildren; + int nKind, rc = PH7_OK; + if(nDepth > JSON_DEFAULT_MAX_DEPTH) { + /* The blob holds a path without a terminator; add one just long + * enough for JsonThrow's copy, then restore the exact length. */ + sxu32 nSaved = SyBlobLength(pPath); + sxi32 rcAppend = SyBlobAppend(pPath, "\0", 1); + int iErr = JsonThrow(pCtx, JSON_ERROR_DEPTH, "Maximum depth exceeded", 0, 0, + rcAppend == SXRET_OK ? (const char *)SyBlobData(pPath) : ""); + SyBlobLength(pPath) = nSaved; + return iErr; + } + /* JsonFieldSetStr copies before replacing, so a path sourced from this + * same blob stays valid; the field slot itself is never reused below. */ + (void)JsonFieldSetStr(pNode, "path", (const char *)SyBlobData(pPath), (int)SyBlobLength(pPath)); + (void)JsonFieldSetInt(pNode, "depth", nDepth); + nKind = (int)JsonFieldInt(pNode, "kind"); + if(nKind != JSON_NODE_OBJECT && nKind != JSON_NODE_ARRAY) { + return PH7_OK; + } + pChildren = JsonFieldContainer(pNode, "children"); + if(pChildren == 0) { + return PH7_OK; + } + { + struct JsonRepathWalk sWalk; + sWalk.pCtx = pCtx; + sWalk.pPath = pPath; + sWalk.nKind = nKind; + sWalk.nIndex = 0; + sWalk.nDepth = nDepth; + sWalk.rc = PH7_OK; + (void)ph7_array_walk(pChildren, JsonRepathWalker, &sWalk); + rc = sWalk.rc; + } + return rc; +} +/* Start a repath from an explicit path string. */ +static int JsonRepathFrom(ph7_context *pCtx, ph7_value *pNode, const char *zPath, int nDepth) { + SyBlob sPath; + int rc; + if(SyBlobInit(&sPath, &pCtx->pVm->sAllocator) != SXRET_OK) { + PH7_VmMemoryError(pCtx->pVm); + return PH7_ABORT; + } + if(SyBlobAppend(&sPath, zPath ? zPath : "", (sxu32)SyStrlen(zPath ? zPath : "")) != SXRET_OK) { + SyBlobRelease(&sPath); + PH7_VmMemoryError(pCtx->pVm); + return PH7_ABORT; + } + rc = JsonRepath(pCtx, &sPath, pNode, nDepth); + SyBlobRelease(&sPath); + return rc; +} +/* Re-derive paths/depths of a mutated node from its own stored values. */ +static int JsonRepathNode(ph7_context *pCtx, ph7_value *pNode) { + const char *zSrc = JsonFieldStr(pNode, "path", 0); + return JsonRepathFrom(pCtx, pNode, zSrc ? zSrc : "$", (int)JsonFieldInt(pNode, "depth")); +} + +/* Native methods returning a typed array must stamp the value with the same + * element type the declaration uses: the return checker compares nType. */ +static void JsonStampArrayType(ph7_context *pCtx, ph7_value *pArray, const char *zClass) { + SyString s; + sxu32 nType = 0; + if(zClass == 0) { + pArray->nType = MEMOBJ_STRING | MEMOBJ_HASHMAP; + return; + } + SyStringInitFromBuf(&s, zClass, (sxu32)SyStrlen(zClass)); + if(PH7_VmInternType(pCtx->pVm, &s, &nType) == SXRET_OK) { + pArray->nType = nType | MEMOBJ_HASHMAP; + } +} + +/* ------------------------------------------------------------------ */ +/* Serializer */ +/* ------------------------------------------------------------------ */ +typedef struct json_ser json_ser; +struct json_ser { + ph7_context *pCtx; + json_opt *pOpt; + int nDepth; + int nErr; + int nOom; + sxu32 nLine; + sxu32 nCol; + const char *zPath; +}; +static int JsonUtf8Valid(const unsigned char *z, sxu32 n); +static void JsonSerPut(json_ser *pSer, const char *z, int nByte) { + if(pSer->nErr || pSer->nOom) { + return; + } + if(ph7_result_string(pSer->pCtx, z, nByte) != PH7_OK) { + pSer->nOom = 1; + PH7_VmMemoryError(pSer->pCtx->pVm); + } +} +static void JsonSerFail(json_ser *pSer, int nErr, ph7_value *pNode) { + const char *zPath; + if(pSer->nErr) { + return; + } + pSer->nErr = nErr; + pSer->nLine = 0; + pSer->nCol = 0; + /* The node (and its path field) outlives serialization, so no copy is + * needed; JsonThrow copies the string before any further mutation. */ + zPath = JsonFieldStr(pNode, "path", 0); + pSer->zPath = zPath ? zPath : ""; +} +static int JsonUtf8Decode(const unsigned char *z, sxu32 n, sxu32 *pi, sxu32 *pCode) { + unsigned char c = z[*pi]; + sxu32 i = *pi, iCode, k; + int nExtra; + if(c < 0x80) { + *pCode = c; + ++*pi; + return 0; + } + if(c >= 0xC2 && c <= 0xDF) { + nExtra = 1; + iCode = c & 0x1F; + } else if(c >= 0xE0 && c <= 0xEF) { + nExtra = 2; + iCode = c & 0x0F; + } else if(c >= 0xF0 && c <= 0xF4) { + nExtra = 3; + iCode = c & 0x07; + } else { + return 1; + } + if(i + (sxu32)nExtra >= n) { + return 1; + } + for(k = 1 ; k <= (sxu32)nExtra ; ++k) { + if((z[i + k] & 0xC0) != 0x80) { + return 1; + } + iCode = (iCode << 6) | (z[i + k] & 0x3F); + } + if((nExtra == 2 && ((c == 0xE0 && z[i + 1] < 0xA0) || (c == 0xED && z[i + 1] >= 0xA0))) || + (nExtra == 3 && ((c == 0xF0 && z[i + 1] < 0x90) || (c == 0xF4 && z[i + 1] > 0x8F)))) { + return 1; + } + *pi = i + (sxu32)nExtra + 1; + *pCode = iCode; + return 0; +} +/* Append one JSON string literal, honouring every string-related option. + * pNode supplies the error path when the bytes are not valid UTF-8. */ +static void JsonSerString(json_ser *pSer, const char *zIn, int nByte, ph7_value *pNode) { + static const char hex[] = "0123456789ABCDEF"; + char zEsc[8]; + json_opt *pOpt = pSer->pOpt; + const unsigned char *z = (const unsigned char *)zIn; + sxu32 i = 0, iCode; + if(!JsonUtf8Valid(z, (sxu32)nByte)) { + JsonSerFail(pSer, JSON_ERROR_UTF8, pNode); + return; + } + JsonSerPut(pSer, "\"", 1); + while(i < (sxu32)nByte) { + unsigned char c = z[i]; + if(c == '<' && pOpt->hexTag) { + JsonSerPut(pSer, "\\u003C", 6); + ++i; + } else if(c == '>' && pOpt->hexTag) { + JsonSerPut(pSer, "\\u003E", 6); + ++i; + } else if(c == '&' && pOpt->hexAmp) { + JsonSerPut(pSer, "\\u0026", 6); + ++i; + } else if(c == '\'' && pOpt->hexApos) { + JsonSerPut(pSer, "\\u0027", 6); + ++i; + } else if(c == '"' && pOpt->hexQuot) { + JsonSerPut(pSer, "\\u0022", 6); + ++i; + } else if(c == '"') { + JsonSerPut(pSer, "\\\"", 2); + ++i; + } else if(c == '\\') { + JsonSerPut(pSer, "\\\\", 2); + ++i; + } else if(c == '/') { + JsonSerPut(pSer, pOpt->unescapedSlashes ? "/" : "\\/", pOpt->unescapedSlashes ? 1 : 2); + ++i; + } else if(c == '\b') { + JsonSerPut(pSer, "\\b", 2); + ++i; + } else if(c == '\f') { + JsonSerPut(pSer, "\\f", 2); + ++i; + } else if(c == '\n') { + JsonSerPut(pSer, "\\n", 2); + ++i; + } else if(c == '\r') { + JsonSerPut(pSer, "\\r", 2); + ++i; + } else if(c == '\t') { + JsonSerPut(pSer, "\\t", 2); + ++i; + } else if(c < 0x20) { + zEsc[0] = '\\'; zEsc[1] = 'u'; zEsc[2] = '0'; zEsc[3] = '0'; + zEsc[4] = hex[(c >> 4) & 0xF]; zEsc[5] = hex[c & 0xF]; + JsonSerPut(pSer, zEsc, 6); + ++i; + } else if(c >= 0x80 && !pOpt->unescapedUnicode) { + if(JsonUtf8Decode(z, (sxu32)nByte, &i, &iCode) != 0) { + JsonSerFail(pSer, JSON_ERROR_UTF8, pNode); + return; + } else if(iCode < 0x10000) { + zEsc[0] = '\\'; zEsc[1] = 'u'; + zEsc[2] = hex[(iCode >> 12) & 0xF]; zEsc[3] = hex[(iCode >> 8) & 0xF]; + zEsc[4] = hex[(iCode >> 4) & 0xF]; zEsc[5] = hex[iCode & 0xF]; + JsonSerPut(pSer, zEsc, 6); + } else { + sxu32 iV = iCode - 0x10000; + sxu32 iHi = 0xD800 + (iV >> 10), iLo = 0xDC00 + (iV & 0x3FF); + zEsc[0] = '\\'; zEsc[1] = 'u'; + zEsc[2] = hex[(iHi >> 12) & 0xF]; zEsc[3] = hex[(iHi >> 8) & 0xF]; + zEsc[4] = hex[(iHi >> 4) & 0xF]; zEsc[5] = hex[iHi & 0xF]; + JsonSerPut(pSer, zEsc, 6); + zEsc[2] = hex[(iLo >> 12) & 0xF]; zEsc[3] = hex[(iLo >> 8) & 0xF]; + zEsc[4] = hex[(iLo >> 4) & 0xF]; zEsc[5] = hex[iLo & 0xF]; + JsonSerPut(pSer, zEsc, 6); + } + } else { + JsonSerPut(pSer, (const char *)&z[i], 1); + ++i; + } + } + JsonSerPut(pSer, "\"", 1); +} +/* Format a real using the shortest round-trippable representation. */ +static int VmJsonFormatReal(char *zBuf, sxu32 nBufSize, ph7_real rVal) { char *zEnd; sxi32 nPrec, nByte, rc = SXERR_ABORT; + if(!isfinite((double)rVal)) { + return SXERR_ABORT; + } #ifdef __WINNT__ _locale_t pLocale; pLocale = _create_locale(LC_NUMERIC, "C"); @@ -225,7 +762,6 @@ static sxi32 VmJsonFormatReal(char *zBuf, sxu32 nBufSize, ph7_real rVal) { if(pLocale == (locale_t)0) { return SXERR_ABORT; } - /* snprintf has no locale argument; change only this thread, never the host locale. */ pOld = uselocale(pLocale); if(pOld == (locale_t)0) { freelocale(pLocale); @@ -253,332 +789,39 @@ static sxi32 VmJsonFormatReal(char *zBuf, sxu32 nBufSize, ph7_real rVal) { #ifdef __WINNT__ _free_locale(pLocale); #else - /* Restore before freeing the locale, including formatting failures. */ if(uselocale(pOld) == (locale_t)0) { - /* Do not free a locale that may still be active. */ return SXERR_ABORT; } freelocale(pLocale); #endif return rc; } -/* - * Recursion probe used to decide whether a hashmap is a JSON array - * (all integer keys exactly 0..n-1 in iteration order) or a JSON object. - */ -struct json_array_probe { - sxi64 iNext; /* Expected key */ - sxi32 bList; /* FALSE as soon as a non-list key is found */ -}; -static int VmJsonArrayProbe(ph7_value *pKey, ph7_value *pValue, void *pUserData) { - struct json_array_probe *pProbe = (struct json_array_probe *)pUserData; - SXUNUSED(pValue); /* cc warning */ - if(pProbe->bList == 0) { - return PH7_OK; - } - if((pKey->nType & MEMOBJ_INT) == 0 || pKey->x.iVal != pProbe->iNext) { - pProbe->bList = 0; - } else { - pProbe->iNext++; - } - return PH7_OK; -} -/* - * Returns the JSON representation of a value.In other word perform a JSON encoding operation. - * According to wikipedia - * JSON's basic types are: - * Number (double precision floating-point format in JavaScript, generally depends on implementation) - * String (double-quoted Unicode, with backslash escaping) - * Boolean (true or false) - * Array (an ordered sequence of values, comma-separated and enclosed in square brackets; the values - * do not need to be of the same type) - * Object (an unordered collection of key:value pairs with the ':' character separating the key - * and the value, comma-separated and enclosed in curly braces; the keys must be strings and should - * be distinct from each other) - * null (empty) - * Non-significant white space may be added freely around the "structural characters" - * (i.e. the brackets "[{]}", colon ":" and comma ","). - */ -static sxi32 VmJsonEncode( - ph7_value *pIn, /* Encode this value */ - json_private_data *pData /* Context data */ -) { - ph7_context *pCtx = pData->pCtx; - int iFlags = pData->iFlags; - int nByte; - if(ph7_value_is_array(pIn)) { - struct json_array_probe sProbe; - sxi32 bObject, isFirst, bOldObject; - if(pData->nRecCount >= JSON_MAX_DEPTH) { - /* Nesting limit reached, abort encoding immediately */ - pCtx->pVm->json_rc = JSON_ERROR_DEPTH; - pData->bAbort = 1; - return PH7_OK; - } - /* A hashmap is an array only when all keys are 0..n-1 in iteration order */ - sProbe.iNext = 0; - sProbe.bList = 1; - ph7_array_walk(pIn, VmJsonArrayProbe, &sProbe); - bObject = (iFlags & JSON_FORCE_OBJECT) != 0 || sProbe.bList == 0; - isFirst = pData->isFirst; - bOldObject = pData->bObject; - pData->isFirst = 1; - pData->bObject = bObject; - /* Append the opening square bracket or curly braces */ - ph7_result_string(pCtx, bObject ? "{" : "[", (int)sizeof(char)); - pData->nRecCount++; - ph7_array_walk(pIn, VmJsonArrayEncode, pData); - pData->nRecCount--; - if(pData->bAbort == 0) { - /* Append the closing square bracket or curly braces */ - ph7_result_string(pCtx, bObject ? "}" : "]", (int)sizeof(char)); - } - pData->isFirst = isFirst; - pData->bObject = bOldObject; - } else if(ph7_value_is_object(pIn)) { - if(pData->nRecCount >= JSON_MAX_DEPTH) { - /* Nesting limit reached, abort encoding immediately */ - pCtx->pVm->json_rc = JSON_ERROR_DEPTH; - pData->bAbort = 1; - return PH7_OK; - } - if(pIn->x.pOther == 0) { - /* Object-typed NULL value, encode it as an empty object */ - ph7_result_string(pCtx, "{}", (int)sizeof("{}") - 1); - } else { - sxi32 isFirst = pData->isFirst; - sxi32 bOldObject = pData->bObject; - pData->isFirst = 1; - pData->bObject = 1; - /* Append the curly braces */ - ph7_result_string(pCtx, "{", (int)sizeof(char)); - pData->nRecCount++; - ph7_object_walk(pIn, VmJsonObjectEncode, pData); - pData->nRecCount--; - if(pData->bAbort == 0) { - /* Append the closing curly braces */ - ph7_result_string(pCtx, "}", (int)sizeof(char)); - } - pData->isFirst = isFirst; - pData->bObject = bOldObject; - } - } else if(ph7_value_is_void(pIn) || ph7_value_is_resource(pIn) || (pIn->nType & MEMOBJ_NULL)) { - /* null */ - ph7_result_string(pCtx, "null", (int)sizeof("null") - 1); - } else if(ph7_value_is_bool(pIn)) { - int iBool = ph7_value_to_bool(pIn); - int iLen; - /* true/false */ - iLen = iBool ? (int)sizeof("true") : (int)sizeof("false"); - ph7_result_string(pCtx, iBool ? "true" : "false", iLen - 1); - } else if(pIn->nType & MEMOBJ_INT) { - char zBuf[32]; - snprintf(zBuf, sizeof(zBuf), "%lld", (long long)pIn->x.iVal); - ph7_result_string(pCtx, zBuf, (int)SyStrlen(zBuf)); - } else if(pIn->nType & MEMOBJ_REAL) { - char zBuf[64]; -#ifdef __WINNT__ - if(_finite((double)pIn->x.rVal) == 0) { -#else - if(isfinite((double)pIn->x.rVal) == 0) { -#endif - /* JSON has no representation for INF or NAN */ - pCtx->pVm->json_rc = JSON_ERROR_SYNTAX; - pData->bAbort = 1; - return PH7_OK; - } - if(VmJsonFormatReal(zBuf, (sxu32)sizeof(zBuf), pIn->x.rVal) != SXRET_OK) { - pCtx->pVm->json_rc = JSON_ERROR_SYNTAX; - pData->bAbort = 1; - return PH7_OK; - } - ph7_result_string(pCtx, zBuf, (int)SyStrlen(zBuf)); - } else if(ph7_value_is_string(pIn)) { - if((iFlags & JSON_NUMERIC_CHECK) && ph7_value_is_numeric(pIn)) { - const char *zNum; - /* Encodes numeric strings as numbers. */ - PH7_MemObjToReal(pIn); /* Force a numeric cast */ - /* Get a string representation of the number */ - zNum = ph7_value_to_string(pIn, &nByte); - ph7_result_string(pCtx, zNum, nByte); - } else { - /* Encode the string */ - const char *zStr = ph7_value_to_string(pIn, &nByte); - VmJsonAppendString(pCtx, zStr, nByte, iFlags); - } - } else { - /* Unsupported value, encode it as null */ - ph7_result_string(pCtx, "null", (int)sizeof("null") - 1); - } - /* All done */ - return PH7_OK; -} -/* - * The following walker callback is invoked each time we need - * to encode an array to JSON. - */ -static int VmJsonArrayEncode(ph7_value *pKey, ph7_value *pValue, void *pUserData) { - json_private_data *pJson = (json_private_data *)pUserData; - if(!pJson->isFirst) { - /* Append the colon first */ - ph7_result_string(pJson->pCtx, ",", (int)sizeof(char)); - } - if(pJson->bObject) { - /* Outputs an object rather than an array */ - const char *zKey; - int nByte; - /* Extract a string representation of the key */ - zKey = ph7_value_to_string(pKey, &nByte); - /* Append the escaped key and the colon */ - VmJsonAppendString(pJson->pCtx, zKey, nByte, pJson->iFlags); - ph7_result_string(pJson->pCtx, ":", (int)sizeof(char)); - } - /* Encode the value */ - VmJsonEncode(pValue, pJson); - pJson->isFirst = 0; - if(pJson->bAbort) { - return PH7_ABORT; - } - return PH7_OK; -} -/* - * The following walker callback is invoked each time we need to encode - * a class instance [i.e: Object in the PHP jargon] to JSON. - */ -static int VmJsonObjectEncode(const char *zAttr, ph7_value *pValue, void *pUserData) { - json_private_data *pJson = (json_private_data *)pUserData; - if(!pJson->isFirst) { - /* Append the colon first */ - ph7_result_string(pJson->pCtx, ",", (int)sizeof(char)); - } - /* Append the escaped attribute name and the colon first */ - VmJsonAppendString(pJson->pCtx, zAttr, (int)SyStrlen(zAttr), pJson->iFlags); - ph7_result_string(pJson->pCtx, ":", (int)sizeof(char)); - /* Encode the value */ - VmJsonEncode(pValue, pJson); - pJson->isFirst = 0; - if(pJson->bAbort) { - return PH7_ABORT; - } - return PH7_OK; -} -/* - * string json_encode(mixed $value [, int $options = 0 ]) - * Returns a string containing the JSON representation of value. - * Parameters - * $value - * The value being encoded. Can be any type except a resource. - * $options - * Bitmask consisting of: - * JSON_HEX_TAG All < and > are converted to \u003C and \u003E. - * JSON_HEX_AMP All &s are converted to \u0026. - * JSON_HEX_APOS All ' are converted to \u0027. - * JSON_HEX_QUOT All " are converted to \u0022. - * JSON_FORCE_OBJECT Outputs an object rather than an array. - * JSON_NUMERIC_CHECK Encodes numeric strings as numbers. - * JSON_BIGINT_AS_STRING Not used - * JSON_PRETTY_PRINT Use whitespace in returned data to format it. - * JSON_UNESCAPED_SLASHES Don't escape '/' - * JSON_UNESCAPED_UNICODE Not used. - * Return - * Returns a JSON encoded string on success. FALSE otherwise - */ -static int vm_builtin_json_encode(ph7_context *pCtx, int nArg, ph7_value **apArg) { - json_private_data sJson; - ph7_vm *pVm = pCtx->pVm; - /* Clear the JSON error code */ - pVm->json_rc = JSON_ERROR_NONE; - if(nArg < 1) { - /* Missing arguments, return FALSE */ - ph7_result_bool(pCtx, 0); - pVm->json_rc = JSON_ERROR_SYNTAX; - return PH7_OK; - } - /* Prepare the JSON data */ - sJson.nRecCount = 0; - sJson.pCtx = pCtx; - sJson.isFirst = 1; - sJson.iFlags = 0; - sJson.bObject = 0; - sJson.bAbort = 0; - if(nArg > 1 && ph7_value_is_int(apArg[1])) { - /* Extract option flags */ - sJson.iFlags = ph7_value_to_int(apArg[1]); - } - /* Perform the encoding operation */ - VmJsonEncode(apArg[0], &sJson); - if(sJson.bAbort) { - /* Discard any partial output and return FALSE */ - if(pVm->json_rc == JSON_ERROR_NONE) { - pVm->json_rc = JSON_ERROR_DEPTH; - } - ph7_result_bool(pCtx, 0); - } else { - pVm->json_rc = JSON_ERROR_NONE; - } - /* All done */ - return PH7_OK; -} -/* - * int json_last_error(void) - * Returns the last error (if any) occurred during the last JSON encoding/decoding. - * Parameters - * None - * Return - * Returns an integer, the value can be one of the following constants: - * JSON_ERROR_NONE No error has occurred. - * JSON_ERROR_DEPTH The maximum stack depth has been exceeded. - * JSON_ERROR_STATE_MISMATCH Invalid or malformed JSON. - * JSON_ERROR_CTRL_CHAR Control character error, possibly incorrectly encoded. - * JSON_ERROR_SYNTAX Syntax error. - * JSON_ERROR_UTF8_CHECK Malformed UTF-8 characters. - */ -static int vm_builtin_json_last_error(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_vm *pVm = pCtx->pVm; - /* Return the error code */ - ph7_result_int(pCtx, pVm->json_rc); - SXUNUSED(nArg); /* cc warning */ - SXUNUSED(apArg); - return PH7_OK; -} -/* - * Return TRUE if the given character is an ASCII digit. - */ -static sxi32 VmJsonIsDigit(sxi32 c) { - return c >= '0' && c <= '9'; -} -/* - * Validate and consume a JSON number from the stream. - * The JSON grammar allows an optional minus sign, no leading zeros, - * an optional fraction and an optional exponent. - */ +/* Validate a JSON number lexeme (used by numericCheck). */ static sxi32 VmJsonScanNumber(SyStream *pStream) { const unsigned char *zText = pStream->zText; const unsigned char *zEnd = pStream->zEnd; if(zText < zEnd && zText[0] == '-') { zText++; } - if(zText >= zEnd || VmJsonIsDigit(zText[0]) == 0) { + if(zText >= zEnd || zText[0] < '0' || zText[0] > '9') { return SXERR_SYNTAX; } if(zText[0] == '0') { zText++; - if(zText < zEnd && VmJsonIsDigit(zText[0])) { - /* Leading zeros are not allowed */ + if(zText < zEnd && zText[0] >= '0' && zText[0] <= '9') { return SXERR_SYNTAX; } } else { - while(zText < zEnd && VmJsonIsDigit(zText[0])) { + while(zText < zEnd && zText[0] >= '0' && zText[0] <= '9') { zText++; } } if(zText < zEnd && zText[0] == '.') { zText++; - if(zText >= zEnd || VmJsonIsDigit(zText[0]) == 0) { - /* Missing fractional digits */ + if(zText >= zEnd || zText[0] < '0' || zText[0] > '9') { return SXERR_SYNTAX; } - while(zText < zEnd && VmJsonIsDigit(zText[0])) { + while(zText < zEnd && zText[0] >= '0' && zText[0] <= '9') { zText++; } } @@ -587,160 +830,328 @@ static sxi32 VmJsonScanNumber(SyStream *pStream) { if(zText < zEnd && (zText[0] == '+' || zText[0] == '-')) { zText++; } - if(zText >= zEnd || VmJsonIsDigit(zText[0]) == 0) { - /* Missing exponent digits */ + if(zText >= zEnd || zText[0] < '0' || zText[0] > '9') { return SXERR_SYNTAX; } - while(zText < zEnd && VmJsonIsDigit(zText[0])) { + while(zText < zEnd && zText[0] >= '0' && zText[0] <= '9') { zText++; } } pStream->zText = zText; return SXRET_OK; } -/* - * Tokenize an entire JSON input. - * Get a single low-level token from the input file. - * Update the stream pointer so that it points to the first - * character beyond the extracted token. - */ -static sxi32 VmJsonTokenize(SyStream *pStream, SyToken *pToken, void *pUserData, void *pCtxData) { - int *pJsonErr = (int *)pUserData; - SyString *pStr; - int c; - SXUNUSED(pCtxData); /* cc warning */ - /* Ignore leading JSON white spaces only: space, tab, carriage return and line feed */ - while(pStream->zText < pStream->zEnd) { - c = pStream->zText[0]; - if(c == ' ' || c == '\t' || c == '\r') { - pStream->zText++; - } else if(c == '\n') { - /* Update line counter */ - pStream->nLine++; - pStream->zText++; - } else { - break; +static int JsonIsNumberLexeme(const char *z, int nByte) { + SyStream s; + if(nByte < 1) { + return 0; + } + SyZero(&s, sizeof(s)); + s.zText = (const unsigned char *)z; + s.zEnd = s.zText + nByte; + if(VmJsonScanNumber(&s) != SXRET_OK) { + return 0; + } + return s.zText == s.zEnd; +} +static void JsonSerIndent(json_ser *pSer, int nLevel) { + int i, n; + for(n = 0 ; n < nLevel ; ++n) { + for(i = 0 ; i < pSer->pOpt->indentLen ; ++i) { + JsonSerPut(pSer, &pSer->pOpt->indent[i], 1); } } +} +struct JsonSerWalk { + json_ser *pSer; + int nKind; + int nCount; + int nFirst; +}; +static void JsonSerNode(json_ser *pSer, ph7_value *pNode); +static int JsonSerWalker(ph7_value *pKey, ph7_value *pValue, void *pUserData) { + struct JsonSerWalk *pWalk = (struct JsonSerWalk *)pUserData; + json_ser *pSer = pWalk->pSer; + json_opt *pOpt = pSer->pOpt; + if(pSer->nErr || pSer->nOom) { + return 1; + } + if(!pWalk->nFirst) { + JsonSerPut(pSer, ",", 1); + if(pOpt->prettyPrint) { + JsonSerPut(pSer, "\n", 1); + } + } + pWalk->nFirst = 0; + if(pOpt->prettyPrint) { + JsonSerIndent(pSer, pSer->nDepth); + } + if(pWalk->nKind == JSON_NODE_OBJECT) { + const char *zKey; + int nKey; + if(pKey == 0) { + return 0; + } + zKey = ph7_value_to_string(pKey, &nKey); + if(ph7_context_status(pSer->pCtx) != PH7_OK) { + pSer->nOom = 1; + return 1; + } + JsonSerString(pSer, zKey, nKey, pValue); + if(pOpt->prettyPrint) { + JsonSerPut(pSer, ": ", 2); + } else { + JsonSerPut(pSer, ":", 1); + } + } + JsonSerNode(pSer, pValue); + return 0; +} +static void JsonSerNode(json_ser *pSer, ph7_value *pNode) { + int nKind = (int)JsonFieldInt(pNode, "kind"); + json_opt *pOpt = pSer->pOpt; + if(pSer->nErr || pSer->nOom) { + return; + } + switch(nKind) { + case JSON_NODE_OBJECT: + case JSON_NODE_ARRAY: { + ph7_value *pChildren; + int nCount; + struct JsonSerWalk sWalk; + /* Match the parser: only containers consume a depth level. A leaf + * at maxDepth is accepted by both sides of the round trip. */ + if(pSer->nDepth >= pOpt->maxDepth) { + JsonSerFail(pSer, JSON_ERROR_DEPTH, pNode); + return; + } + pChildren = JsonFieldContainer(pNode, "children"); + nCount = pChildren ? (int)ph7_array_count(pChildren) : 0; + JsonSerPut(pSer, nKind == JSON_NODE_OBJECT ? "{" : "[", 1); + if(nCount > 0) { + if(pOpt->prettyPrint) { + JsonSerPut(pSer, "\n", 1); + } + ++pSer->nDepth; + sWalk.pSer = pSer; + sWalk.nKind = nKind; + sWalk.nCount = nCount; + sWalk.nFirst = 1; + if(pChildren) { + (void)ph7_array_walk(pChildren, JsonSerWalker, &sWalk); + } + --pSer->nDepth; + if(pOpt->prettyPrint) { + JsonSerPut(pSer, "\n", 1); + JsonSerIndent(pSer, pSer->nDepth); + } + } + JsonSerPut(pSer, nKind == JSON_NODE_OBJECT ? "}" : "]", 1); + break; + } + case JSON_NODE_STRING: { + int nLen; + const char *zText = JsonFieldStr(pNode, "text", &nLen); + if(pOpt->numericCheck && JsonIsNumberLexeme(zText, nLen)) { + JsonSerPut(pSer, zText, nLen); + } else { + JsonSerString(pSer, zText, nLen, pNode); + } + break; + } + case JSON_NODE_NUMBER: { + int nLen; + const char *zRaw = JsonFieldStr(pNode, "rawNumber", &nLen); + if(nLen > 0 && !JsonIsNumberLexeme(zRaw, nLen)) { + JsonSerFail(pSer, JSON_ERROR_SYNTAX, pNode); + break; + } + if(nLen > 0) { + JsonSerPut(pSer, zRaw, nLen); + } else { + char zBuf[64]; + if(VmJsonFormatReal(zBuf, sizeof(zBuf), JsonFieldDouble(pNode, "realValue")) == SXRET_OK) { + JsonSerPut(pSer, zBuf, (int)SyStrlen(zBuf)); + } else { + JsonSerFail(pSer, JSON_ERROR_SYNTAX, pNode); + } + } + break; + } + case JSON_NODE_BOOLEAN: { + int bVal = JsonFieldBool(pNode, "boolValue"); + JsonSerPut(pSer, bVal ? "true" : "false", bVal ? 4 : 5); + break; + } + case JSON_NODE_NULL_NODE: + default: + JsonSerPut(pSer, "null", 4); + break; + } +} + +/* Serialize a node into the current call result. */ +static int JsonSerialize(ph7_context *pCtx, ph7_value *pNode, ph7_value *pOptions) { + json_opt sOpt; + json_ser sSer; + int rc; + if(pNode == 0 || (pNode->nType & MEMOBJ_OBJ) == 0 || pNode->x.pOther == 0) { + return JsonThrow(pCtx, JSON_ERROR_TYPE_MISMATCH, "JsonNode expected", 0, 0, ""); + } + rc = JsonOptLoad(pCtx, pOptions, &sOpt); + if(rc != PH7_OK) { + return rc; + } + SyZero(&sSer, sizeof(sSer)); + sSer.pCtx = pCtx; + sSer.pOpt = &sOpt; + JsonSerNode(&sSer, pNode); + if(sSer.nOom) { + return PH7_ABORT; + } + if(sSer.nErr) { + return JsonThrow(pCtx, sSer.nErr, JsonErrorDescription(sSer.nErr), + sSer.nLine, sSer.nCol, sSer.zPath); + } + return PH7_OK; +} + +/* ------------------------------------------------------------------ */ +/* Tokenizer with comments support */ +/* ------------------------------------------------------------------ */ +typedef struct json_lex json_lex; +struct json_lex { + int iErr; + int allowComments; +}; +static sxi32 VmJsonTokenize(SyStream *pStream, SyToken *pToken, void *pUserData, void *pCtxData) { + json_lex *pLex = (json_lex *)pUserData; + SyString *pStr; + int c; + SXUNUSED(pCtxData); + for(;;) { + while(pStream->zText < pStream->zEnd) { + c = pStream->zText[0]; + if(c == ' ' || c == '\t' || c == '\r') { + pStream->zText++; + } else if(c == '\n') { + pStream->nLine++; + pStream->zText++; + } else { + break; + } + } + if(!pLex->allowComments || pStream->zEnd - pStream->zText < 2 || pStream->zText[0] != '/') { + break; + } + if(pStream->zText[1] == '/') { + pStream->zText += 2; + while(pStream->zText < pStream->zEnd && pStream->zText[0] != '\n') { + pStream->zText++; + } + continue; + } + if(pStream->zText[1] == '*') { + pStream->zText += 2; + while(pStream->zEnd - pStream->zText >= 2 && + !(pStream->zText[0] == '*' && pStream->zText[1] == '/')) { + if(pStream->zText[0] == '\n') { + pStream->nLine++; + } + pStream->zText++; + } + if(pStream->zEnd - pStream->zText < 2) { + pLex->iErr = JSON_ERROR_SYNTAX; + return SXERR_ABORT; + } + pStream->zText += 2; + continue; + } + break; + } if(pStream->zText >= pStream->zEnd) { - /* End of input reached */ return SXERR_EOF; } - /* Record token starting position and line */ pToken->nLine = pStream->nLine; pToken->pUserData = 0; pStr = &pToken->sData; SyStringInitFromBuf(pStr, pStream->zText, 0); if(pStream->zText[0] == '{' || pStream->zText[0] == '[' || pStream->zText[0] == '}' || pStream->zText[0] == ']' || pStream->zText[0] == ':' || pStream->zText[0] == ',') { - /* Single character */ c = pStream->zText[0]; - /* Set token type */ switch(c) { - case '[': - pToken->nType = JSON_TK_OSB; - break; - case '{': - pToken->nType = JSON_TK_OCB; - break; - case '}': - pToken->nType = JSON_TK_CCB; - break; - case ']': - pToken->nType = JSON_TK_CSB; - break; - case ':': - pToken->nType = JSON_TK_COLON; - break; - case ',': - pToken->nType = JSON_TK_COMMA; - break; - default: - break; + case '[': pToken->nType = JSON_TK_OSB; break; + case '{': pToken->nType = JSON_TK_OCB; break; + case '}': pToken->nType = JSON_TK_CCB; break; + case ']': pToken->nType = JSON_TK_CSB; break; + case ':': pToken->nType = JSON_TK_COLON; break; + case ',': pToken->nType = JSON_TK_COMMA; break; + default: break; } - /* Advance the stream cursor */ pStream->zText++; } else if(pStream->zText[0] == '"') { - /* JSON string, skip the opening double quote */ pStream->zText++; pStr->zString = (const char *)pStream->zText; while(pStream->zText < pStream->zEnd) { c = pStream->zText[0]; if(c == '"') { - /* Closing double quote */ break; } if((unsigned char)c < 0x20) { - /* Unescaped control character */ - *pJsonErr = JSON_ERROR_CTRL_CHAR; + pLex->iErr = JSON_ERROR_CTRL_CHAR; return SXERR_ABORT; } if(c == '\\') { - /* Skip the escaped character (including \" and \\) */ pStream->zText++; if(pStream->zText >= pStream->zEnd) { - *pJsonErr = JSON_ERROR_SYNTAX; + pLex->iErr = JSON_ERROR_SYNTAX; return SXERR_ABORT; } } pStream->zText++; } if(pStream->zText >= pStream->zEnd) { - /* Missing closing '"' */ - *pJsonErr = JSON_ERROR_SYNTAX; + pLex->iErr = JSON_ERROR_SYNTAX; return SXERR_ABORT; } pToken->nType = JSON_TK_STR; - pStream->zText++; /* Jump the closing double quote */ - } else if(pStream->zText[0] == '-' || VmJsonIsDigit(pStream->zText[0])) { - /* Number */ + pStream->zText++; + } else if(pStream->zText[0] == '-' || (pStream->zText[0] >= '0' && pStream->zText[0] <= '9')) { if(VmJsonScanNumber(pStream) != SXRET_OK) { - *pJsonErr = JSON_ERROR_SYNTAX; + pLex->iErr = JSON_ERROR_SYNTAX; return SXERR_ABORT; } pToken->nType = JSON_TK_NUM; } else if(XLEX_IN_LEN(pStream) >= sizeof("true") - 1 && SyStrncmp((const char *)pStream->zText, "true", sizeof("true") - 1) == 0) { - /* boolean true */ pToken->nType = JSON_TK_TRUE; - /* Advance the stream cursor */ pStream->zText += sizeof("true") - 1; } else if(XLEX_IN_LEN(pStream) >= sizeof("false") - 1 && SyStrncmp((const char *)pStream->zText, "false", sizeof("false") - 1) == 0) { - /* boolean false */ pToken->nType = JSON_TK_FALSE; - /* Advance the stream cursor */ pStream->zText += sizeof("false") - 1; } else if(XLEX_IN_LEN(pStream) >= sizeof("null") - 1 && SyStrncmp((const char *)pStream->zText, "null", sizeof("null") - 1) == 0) { - /* NULL */ pToken->nType = JSON_TK_NULL; - /* Advance the stream cursor */ pStream->zText += sizeof("null") - 1; } else { - /* Unexpected token */ pToken->nType = JSON_TK_INVALID; - *pJsonErr = JSON_ERROR_SYNTAX; - /* Abort processing immediately */ + pLex->iErr = JSON_ERROR_SYNTAX; return SXERR_ABORT; } - /* record token length */ pStr->nByte = (sxu32)((const char *)pStream->zText - pStr->zString); if(pToken->nType == JSON_TK_STR) { pStr->nByte--; } - /* Return to the lexer */ return SXRET_OK; } -/* - * Parse exactly four hexadecimal digits. - * Return SXRET_OK and store the value on success, SXERR_SYNTAX otherwise. - */ + +/* ------------------------------------------------------------------ */ +/* String dequoting + UTF-8 validation */ +/* ------------------------------------------------------------------ */ static sxi32 VmJsonHex4(const unsigned char *zIn, sxu32 *pVal) { - sxu32 iVal = 0; - sxu32 i; + sxu32 iVal = 0, i; sxi32 c; - for(i = 0; i < 4; ++i) { + for(i = 0 ; i < 4 ; ++i) { c = SyHexToint(zIn[i]); if(c < 0) { return SXERR_SYNTAX; @@ -750,80 +1161,51 @@ static sxi32 VmJsonHex4(const unsigned char *zIn, sxu32 *pVal) { *pVal = iVal; return SXRET_OK; } -/* - * Append a Unicode code point as UTF-8. - */ static void VmJsonAppendCodePoint(ph7_value *pWorker, sxu32 iCode) { char zBuf[4]; sxu32 nByte; if(iCode < 0x80) { - zBuf[0] = (char)iCode; - nByte = 1; + zBuf[0] = (char)iCode; nByte = 1; } else if(iCode < 0x800) { zBuf[0] = (char)(0xC0 | (iCode >> 6)); - zBuf[1] = (char)(0x80 | (iCode & 0x3F)); - nByte = 2; + zBuf[1] = (char)(0x80 | (iCode & 0x3F)); nByte = 2; } else if(iCode < 0x10000) { zBuf[0] = (char)(0xE0 | (iCode >> 12)); zBuf[1] = (char)(0x80 | ((iCode >> 6) & 0x3F)); - zBuf[2] = (char)(0x80 | (iCode & 0x3F)); - nByte = 3; + zBuf[2] = (char)(0x80 | (iCode & 0x3F)); nByte = 3; } else { zBuf[0] = (char)(0xF0 | (iCode >> 18)); zBuf[1] = (char)(0x80 | ((iCode >> 12) & 0x3F)); zBuf[2] = (char)(0x80 | ((iCode >> 6) & 0x3F)); - zBuf[3] = (char)(0x80 | (iCode & 0x3F)); - nByte = 4; + zBuf[3] = (char)(0x80 | (iCode & 0x3F)); nByte = 4; } - ph7_value_string(pWorker, zBuf, nByte); + (void)ph7_value_string(pWorker, zBuf, (int)nByte); } -/* - * Dequote [i.e: Resolve all backslash escapes ] a JSON string and store - * the result in the given ph7_value. - */ static sxi32 VmJsonDequoteString(const SyString *pStr, ph7_value *pWorker, int *pErr) { const unsigned char *zIn = (const unsigned char *)pStr->zString; const unsigned char *zEnd = &zIn[pStr->nByte]; const unsigned char *zCur; sxu32 iCode, iLow; int c; - /* Mark the value as a string */ - ph7_value_string(pWorker, "", 0); /* Empty string */ + (void)ph7_value_string(pWorker, "", 0); while(zIn < zEnd) { if(zIn[0] == '\\') { zIn++; if(zIn >= zEnd) { - /* Missing escaped character */ *pErr = JSON_ERROR_SYNTAX; return SXERR_ABORT; } c = zIn[0]; zIn++; switch(c) { - case '"': - ph7_value_string(pWorker, "\"", (int)sizeof(char)); - break; - case '\\': - ph7_value_string(pWorker, "\\", (int)sizeof(char)); - break; - case '/': - ph7_value_string(pWorker, "/", (int)sizeof(char)); - break; - case 'b': - ph7_value_string(pWorker, "\b", (int)sizeof(char)); - break; - case 'f': - ph7_value_string(pWorker, "\f", (int)sizeof(char)); - break; - case 'n': - ph7_value_string(pWorker, "\n", (int)sizeof(char)); - break; - case 'r': - ph7_value_string(pWorker, "\r", (int)sizeof(char)); - break; - case 't': - ph7_value_string(pWorker, "\t", (int)sizeof(char)); - break; + case '"': (void)ph7_value_string(pWorker, "\"", 1); break; + case '\\': (void)ph7_value_string(pWorker, "\\", 1); break; + case '/': (void)ph7_value_string(pWorker, "/", 1); break; + case 'b': (void)ph7_value_string(pWorker, "\b", 1); break; + case 'f': (void)ph7_value_string(pWorker, "\f", 1); break; + case 'n': (void)ph7_value_string(pWorker, "\n", 1); break; + case 'r': (void)ph7_value_string(pWorker, "\r", 1); break; + case 't': (void)ph7_value_string(pWorker, "\t", 1); break; case 'u': if((zEnd - zIn) < 4 || VmJsonHex4(zIn, &iCode) != SXRET_OK) { *pErr = JSON_ERROR_SYNTAX; @@ -831,7 +1213,6 @@ static sxi32 VmJsonDequoteString(const SyString *pStr, ph7_value *pWorker, int * } zIn += 4; if(iCode >= 0xD800 && iCode <= 0xDBFF) { - /* High surrogate, a low surrogate must follow */ if((zEnd - zIn) < 6 || zIn[0] != '\\' || zIn[1] != 'u' || VmJsonHex4(&zIn[2], &iLow) != SXRET_OK || iLow < 0xDC00 || iLow > 0xDFFF) { @@ -841,19 +1222,16 @@ static sxi32 VmJsonDequoteString(const SyString *pStr, ph7_value *pWorker, int * zIn += 6; iCode = 0x10000 + ((iCode - 0xD800) << 10) + (iLow - 0xDC00); } else if(iCode >= 0xDC00 && iCode <= 0xDFFF) { - /* Lone low surrogate */ *pErr = JSON_ERROR_SYNTAX; return SXERR_ABORT; } VmJsonAppendCodePoint(pWorker, iCode); break; default: - /* Unknown escape sequence */ *pErr = JSON_ERROR_SYNTAX; return SXERR_ABORT; } } else if(zIn[0] < 0x20) { - /* Unescaped control character */ *pErr = JSON_ERROR_CTRL_CHAR; return SXERR_ABORT; } else { @@ -861,26 +1239,179 @@ static sxi32 VmJsonDequoteString(const SyString *pStr, ph7_value *pWorker, int * while(zIn < zEnd && zIn[0] != '\\' && zIn[0] >= 0x20) { zIn++; } - /* Append chunk verbatim */ - ph7_value_string(pWorker, (const char *)zCur, (int)(zIn - zCur)); + (void)ph7_value_string(pWorker, (const char *)zCur, (int)(zIn - zCur)); } } return SXRET_OK; } -/* - * Decode a JSON numeric token. - * Integers are decoded exactly when they fit in a signed 64-bit integer. - * Out of range integers are converted to doubles, or kept as strings when - * the JSON_BIGINT_AS_STRING option is set. Numeric literals that overflow - * to a non-finite double are rejected as syntax errors. - */ -static sxi32 VmJsonDecodeNumber(const SyString *pStr, ph7_value *pWorker, sxi32 iFlags, int *pErr) { +static int JsonUtf8Valid(const unsigned char *z, sxu32 n) { + sxu32 i = 0; + while(i < n) { + sxu32 k, iNeed; + unsigned char c = z[i]; + if(c < 0x80) { ++i; continue; } + if(c >= 0xC2 && c <= 0xDF) iNeed = 1; + else if(c >= 0xE0 && c <= 0xEF) iNeed = 2; + else if(c >= 0xF0 && c <= 0xF4) iNeed = 3; + else return 0; + if(i + iNeed >= n) return 0; + for(k = 1 ; k <= iNeed ; ++k) { + if((z[i + k] & 0xC0) != 0x80) return 0; + } + if(iNeed == 2 && ((c == 0xE0 && z[i + 1] < 0xA0) || (c == 0xED && z[i + 1] >= 0xA0))) return 0; + if(iNeed == 3 && ((c == 0xF0 && z[i + 1] < 0x90) || (c == 0xF4 && z[i + 1] > 0x8F))) return 0; + i += iNeed + 1; + } + return 1; +} + +/* Return TRUE when a numeric lexeme denotes an exact signed 64-bit integer. + * The decimal digits are parsed directly (not through double) so exponent and + * fractional forms such as 12e2, 1.0 or -3E1 stay exact; values with a real + * fractional part or outside int64 are rejected. */ +static int JsonLexemeInt64(const char *z, sxu32 nByte, ph7_int64 *pOut) { + sxu32 i, k, nInt = 0, nTotal = 0; + sxi64 iExp = 0, iShift; + sxi32 bNeg = 0, bFrac = 0, bZero = 1; + sxu64 uVal = 0, uLimit; + if(nByte < 1) { + return 0; + } + i = 0; + if(z[0] == '-') { + bNeg = 1; + i = 1; + } + /* First pass: count integer/all mantissa digits and detect an all-zero + * mantissa (0e9999 is still exactly zero). */ + for(; i < nByte && z[i] != 'e' && z[i] != 'E'; ++i) { + if(z[i] == '.') { + bFrac = 1; + continue; + } + if(z[i] < '0' || z[i] > '9') { + return 0; + } + if(z[i] != '0') { + bZero = 0; + } + ++nTotal; + if(bFrac == 0) { + ++nInt; + } + } + if(nTotal < 1) { + return 0; + } + if(i < nByte) { + sxi32 bExpNeg = 0; + ++i; /* 'e' or 'E' */ + if(i < nByte && (z[i] == '+' || z[i] == '-')) { + bExpNeg = z[i] == '-'; + ++i; + } + if(i >= nByte) { + return 0; + } + for(; i < nByte; ++i) { + if(z[i] < '0' || z[i] > '9') { + return 0; + } + /* Saturate: any exponent this large already decides the result. */ + if(iExp < 1000) { + iExp = iExp * 10 + (sxu32)(z[i] - '0'); + } + } + if(bExpNeg) { + iExp = -iExp; + } + } + if(bZero) { + *pOut = 0; + return 1; + } + /* Digits before the decimal point after applying the exponent. */ + iShift = (sxi64)nInt + iExp; + if(iShift <= 0) { + return 0; /* Nonzero value smaller than one. */ + } + uLimit = bNeg ? 9223372036854775808ULL : 9223372036854775807ULL; + k = 0; + for(i = bNeg ? 1 : 0; i < nByte && z[i] != 'e' && z[i] != 'E'; ++i) { + if(z[i] == '.') { + continue; + } + if((sxi64)k < iShift) { + sxu32 iDigit = (sxu32)(z[i] - '0'); + if(uVal > (uLimit - iDigit) / 10) { + return 0; + } + uVal = uVal * 10 + iDigit; + } else if(z[i] != '0') { + return 0; /* Discarded fractional digits must all be zero. */ + } + ++k; + } + for(; (sxi64)k < iShift; ++k) { + if(uVal > uLimit / 10) { + return 0; + } + uVal *= 10; + } + if(bNeg) { + if(uVal == 9223372036854775808ULL) { + *pOut = (-9223372036854775807LL - 1); + } else { + *pOut = -(ph7_int64)uVal; + } + } else { + *pOut = (ph7_int64)uVal; + } + return 1; +} + +/* Decode a numeric lexeme in the C locale into a NUMBER node's scalar fields. + * Both the parser and the raw-number constructor use this so that rawNumber, + * realValue and intValue always describe the same lexeme. */ +static int JsonNumberFromLexeme(ph7_context *pCtx, ph7_value *pNode, + const char *zNum, sxu32 nByte, const char *zPath) { + char *zEnd; + double rVal; + ph7_int64 iVal; +#ifdef __WINNT__ + _locale_t pLocale = _create_locale(LC_NUMERIC, "C"); + if(pLocale == (_locale_t)0) { + return JsonThrow(pCtx, JSON_ERROR_SYNTAX, "Syntax error", 0, 0, zPath); + } +#else + locale_t pLocale = newlocale(LC_NUMERIC_MASK, "C", (locale_t)0); + if(pLocale == (locale_t)0) { + return JsonThrow(pCtx, JSON_ERROR_SYNTAX, "Syntax error", 0, 0, zPath); + } +#endif +#ifdef __WINNT__ + rVal = _strtod_l(zNum, &zEnd, pLocale); + _free_locale(pLocale); +#else + rVal = strtod_l(zNum, &zEnd, pLocale); + freelocale(pLocale); +#endif + if(zEnd != &zNum[nByte] || !isfinite(rVal)) { + return JsonThrow(pCtx, JSON_ERROR_SYNTAX, "Syntax error", 0, 0, zPath); + } + JsonFieldSetDouble(pNode, "realValue", rVal); + if(JsonLexemeInt64(zNum, nByte, &iVal)) { + JsonFieldSetInt(pNode, "intValue", iVal); + } + return PH7_OK; +} +/* Decode a numeric token into a NUMBER node (or a STRING node for bigintAsString). */ +static int JsonDecodeNumber(ph7_context *pCtx, const SyString *pStr, json_opt *pOpt, + const char *zPath, ph7_value **ppNode) { const char *zNum = pStr->zString; - sxu32 nByte = pStr->nByte; - sxu32 i; - sxi32 bReal = 0; - /* Check for a fraction or an exponent */ - for(i = 0; i < nByte; ++i) { + sxu32 nByte = pStr->nByte, i; + int bReal = 0; + for(i = 0 ; i < nByte ; ++i) { if(zNum[i] == '.' || zNum[i] == 'e' || zNum[i] == 'E') { bReal = 1; break; @@ -891,12 +1422,9 @@ static sxi32 VmJsonDecodeNumber(const SyString *pStr, ph7_value *pWorker, sxi32 sxu64 uVal = 0, uLimit; sxi64 iVal; i = 0; - if(zNum[0] == '-') { - bNeg = 1; - i++; - } + if(zNum[0] == '-') { bNeg = 1; i++; } uLimit = bNeg ? 9223372036854775808ULL : 9223372036854775807ULL; - for(; i < nByte; ++i) { + for(; i < nByte ; ++i) { sxu32 iDigit = (sxu32)(zNum[i] - '0'); if(uVal > (uLimit - iDigit) / 10) { bOverflow = 1; @@ -905,470 +1433,1753 @@ static sxi32 VmJsonDecodeNumber(const SyString *pStr, ph7_value *pWorker, sxi32 uVal = uVal * 10 + iDigit; } if(bOverflow == 0) { + ph7_value *pNode = JsonNewNode(pCtx, JCLS_NUMBER, JSON_NODE_NUMBER, zPath); + if(pNode == 0) { + return PH7_ABORT; + } if(bNeg) { - if(uVal == 9223372036854775808ULL) { - iVal = (-9223372036854775807LL - 1); - } else { - iVal = -(sxi64)uVal; - } + if(uVal == 9223372036854775808ULL) iVal = (-9223372036854775807LL - 1); + else iVal = -(sxi64)uVal; } else { iVal = (sxi64)uVal; } - ph7_value_int64(pWorker, iVal); - return SXRET_OK; + JsonFieldSetInt(pNode, "intValue", iVal); + JsonFieldSetDouble(pNode, "realValue", (double)iVal); + JsonFieldSetStr(pNode, "rawNumber", zNum, (int)nByte); + *ppNode = pNode; + return PH7_OK; } - if(iFlags & JSON_BIGINT_AS_STRING) { - /* Keep the exact integer representation */ - ph7_value_string(pWorker, zNum, (int)nByte); - return SXRET_OK; + if(pOpt->bigintAsString) { + ph7_value *pNode = JsonNewNode(pCtx, JCLS_STRING, JSON_NODE_STRING, zPath); + if(pNode == 0) { + return PH7_ABORT; + } + JsonFieldSetStr(pNode, "text", zNum, (int)nByte); + JsonFieldSetStr(pNode, "rawNumber", zNum, (int)nByte); + *ppNode = pNode; + return PH7_OK; } } { - char *zEnd; - double rVal; -#ifdef __WINNT__ - _locale_t pLocale = _create_locale(LC_NUMERIC, "C"); - if(pLocale == (_locale_t)0) { -#else - locale_t pLocale = newlocale(LC_NUMERIC_MASK, "C", (locale_t)0); - if(pLocale == (locale_t)0) { -#endif - *pErr = JSON_ERROR_SYNTAX; - return SXERR_ABORT; + ph7_value *pNode = JsonNewNode(pCtx, JCLS_NUMBER, JSON_NODE_NUMBER, zPath); + int rc; + if(pNode == 0) { + return PH7_ABORT; } -#ifdef __WINNT__ - rVal = _strtod_l(zNum, &zEnd, pLocale); - _free_locale(pLocale); - if(zEnd != &zNum[nByte] || _finite(rVal) == 0) { -#else - rVal = strtod_l(zNum, &zEnd, pLocale); - freelocale(pLocale); - if(zEnd != &zNum[nByte] || isfinite(rVal) == 0) { -#endif - /* Malformed number or a value that overflows to INF */ - *pErr = JSON_ERROR_SYNTAX; - return SXERR_ABORT; + rc = JsonNumberFromLexeme(pCtx, pNode, zNum, nByte, zPath); + if(rc != PH7_OK) { + return rc; } - ph7_value_double(pWorker, rVal); + JsonFieldSetStr(pNode, "rawNumber", zNum, (int)nByte); + *ppNode = pNode; + return PH7_OK; } - return SXRET_OK; } -/* - * Returns a ph7_value holding the image of a JSON string. In other word perform a JSON decoding operation. - * According to wikipedia - * JSON's basic types are: - * Number (double precision floating-point format in JavaScript, generally depends on implementation) - * String (double-quoted Unicode, with backslash escaping) - * Boolean (true or false) - * Array (an ordered sequence of values, comma-separated and enclosed in square brackets; the values - * do not need to be of the same type) - * Object (an unordered collection of key:value pairs with the ':' character separating the key - * and the value, comma-separated and enclosed in curly braces; the keys must be strings and should - * be distinct from each other) - * null (empty) - * Non-significant white space may be added freely around the "structural characters" which are the brackets "[{]}", colon ":" and comma ",". - */ -static sxi32 VmJsonDecode( - json_decoder *pDecoder, /* JSON decoder */ - ph7_value *pArrayKey /* Key for the decoded array */ -) { - ph7_value *pWorker; /* Worker variable */ - sxi32 rc; - if(pDecoder->pIn >= pDecoder->pEnd) { - /* Unexpected end of input */ - *pDecoder->pErr = JSON_ERROR_SYNTAX; - return SXERR_ABORT; + +/* ------------------------------------------------------------------ */ +/* Parser (DOM-building consumer) */ +/* ------------------------------------------------------------------ */ +typedef struct json_parse json_parse; +struct json_parse { + ph7_context *pCtx; + SyToken *pIn; + SyToken *pEnd; + json_opt *pOpt; + const unsigned char *zInput; + SyBlob path; /* Single growable path buffer shared by the recursion */ +}; +static sxu32 JsonTokenCol(json_parse *pP, SyToken *pTok) { + const unsigned char *z = (const unsigned char *)SyStringData(&pTok->sData); + const unsigned char *p = z; + if(z == 0 || pP->zInput == 0 || z < pP->zInput) { + return 0; } - if(pDecoder->pIn->nType & (JSON_TK_STR | JSON_TK_TRUE | JSON_TK_FALSE | JSON_TK_NULL | JSON_TK_NUM)) { - /* Scalar value */ - pWorker = ph7_context_new_scalar(pDecoder->pCtx); - if(pWorker == 0) { - *pDecoder->pErr = JSON_ERROR_STATE_MISMATCH; - PH7_VmMemoryError(pDecoder->pCtx->pVm); - /* Abort the decoding operation immediately */ - return SXERR_ABORT; + while(p > pP->zInput && p[-1] != '\n') { + --p; + } + /* A string token's data starts after the opening quote; report the quote's + * 1-based column instead of the first content byte's 0-based offset. */ + if(pTok->nType & JSON_TK_STR && z > p) { + --z; + } + return (sxu32)(z - p) + 1; +} +static int JsonParseError(json_parse *pP, SyToken *pTok, int nErr, const char *zMsg, const char *zPath) { + sxu32 nLine = pTok ? pTok->nLine : 0; + sxu32 nCol = pTok ? JsonTokenCol(pP, pTok) : 0; + return JsonThrow(pP->pCtx, nErr, zMsg, nLine, nCol, zPath); +} +/* Walk helper that finds an integer-keyed child. The walker hands out a + * short-lived temporary, so copy into an owned output slot. */ +struct JsonFindInt { + ph7_int64 iTarget; + ph7_value *pOut; + int bFound; +}; +static int JsonFindIntWalker(ph7_value *pKey, ph7_value *pValue, void *pUserData) { + struct JsonFindInt *pFind = (struct JsonFindInt *)pUserData; + if(pKey && ph7_value_is_int(pKey) && ph7_value_to_int64(pKey) == pFind->iTarget) { + (void)PH7_MemObjStore(pValue, pFind->pOut); + pFind->bFound = 1; + return 1; + } + return 0; +} +static ph7_value *JsonArrayGet(ph7_context *pCtx, ph7_value *pChildren, ph7_int64 iIndex) { + struct JsonFindInt sFind; + ph7_value *pOut; + if(pChildren == 0 || iIndex < 0) { + return 0; + } + pOut = ph7_context_new_scalar(pCtx); + if(pOut == 0) { + return 0; + } + sFind.iTarget = iIndex; + sFind.pOut = pOut; + sFind.bFound = 0; + (void)ph7_array_walk(pChildren, JsonFindIntWalker, &sFind); + if(!sFind.bFound) { + ph7_context_release_value(pCtx, pOut); + return 0; + } + return pOut; +} +/* Paths live in one growable blob shared by the parser recursion. The blob + * always ends with a NUL so the current path can be passed to the node + * constructor and to JsonThrow without a copy. */ +#define JSON_PPATH(pP) ((const char *)SyBlobData(&(pP)->path)) +/* Extend the blob with the child suffix at nEnd (parent path length incl. NUL). + * The caller truncates the blob back to nEnd once the child is built. */ +/* Truncating a blob only resets its length; restore the NUL as well so the + * parent path reads back exactly as it did before the child was built. */ +static void JsonParsePathRestore(json_parse *pP, sxu32 nEnd) { + SyBlobLength(&pP->path) = nEnd; + if(nEnd > 0) { + ((char *)SyBlobData(&pP->path))[nEnd - 1] = '\0'; + } +} +static int JsonParsePathChild(json_parse *pP, sxu32 nEnd, int nIndex, + const char *zKey, int nKey) { + sxi32 rc; + SyBlobLength(&pP->path) = nEnd - 1; /* overwrite the parent's terminator */ + if(zKey) { + rc = SyBlobAppend(&pP->path, ".", 1); + if(rc == SXRET_OK) { + rc = SyBlobAppend(&pP->path, zKey, (sxu32)nKey); } - /* Reflect the JSON image */ - if(pDecoder->pIn->nType & JSON_TK_NULL) { - /* Nullify the value.*/ - ph7_value_void(pWorker); - } else if(pDecoder->pIn->nType & (JSON_TK_TRUE | JSON_TK_FALSE)) { - /* Boolean value */ - ph7_value_bool(pWorker, (pDecoder->pIn->nType & JSON_TK_TRUE) ? 1 : 0); - } else if(pDecoder->pIn->nType & JSON_TK_NUM) { - /* Numeric value */ - rc = VmJsonDecodeNumber(&pDecoder->pIn->sData, pWorker, pDecoder->iFlags, pDecoder->pErr); - if(rc == SXERR_ABORT) { - ph7_context_release_value(pDecoder->pCtx, pWorker); - return SXERR_ABORT; - } - } else { - /* Dequote the string */ - rc = VmJsonDequoteString(&pDecoder->pIn->sData, pWorker, pDecoder->pErr); - if(rc == SXERR_ABORT) { - ph7_context_release_value(pDecoder->pCtx, pWorker); - return SXERR_ABORT; - } - } - /* Invoke the consumer callback */ - rc = pDecoder->xConsumer(pDecoder->pCtx, pArrayKey, pWorker, pDecoder->pUserData); - /* Release the worker variable */ - ph7_context_release_value(pDecoder->pCtx, pWorker); - if(rc == SXERR_ABORT) { - return SXERR_ABORT; - } - /* All done,advance the stream cursor */ - pDecoder->pIn++; - } else if(pDecoder->pIn->nType & JSON_TK_OSB /*'[' */) { - ProcJsonConsumer xOld; - void *pOld; - /* Check if we do not nest too much */ - if(pDecoder->rec_count >= pDecoder->rec_depth) { - /* Nesting limit reached,abort decoding immediately */ - *pDecoder->pErr = JSON_ERROR_DEPTH; - return SXERR_ABORT; - } - /* Array representation*/ - pDecoder->pIn++; - /* Create a working array */ - pWorker = ph7_context_new_array(pDecoder->pCtx); - if(pWorker == 0) { - *pDecoder->pErr = JSON_ERROR_STATE_MISMATCH; - PH7_VmMemoryError(pDecoder->pCtx->pVm); - /* Abort the decoding operation immediately */ - return SXERR_ABORT; - } - /* Save the old consumer */ - xOld = pDecoder->xConsumer; - pOld = pDecoder->pUserData; - /* Set the new consumer */ - pDecoder->xConsumer = VmJsonArrayDecoder; - pDecoder->pUserData = pWorker; - pDecoder->rec_count++; - if(pDecoder->pIn < pDecoder->pEnd && (pDecoder->pIn->nType & JSON_TK_CSB) /*']'*/) { - /* Empty array */ - pDecoder->pIn++; - } else { - for(;;) { - /* Decode an array entry */ - rc = VmJsonDecode(pDecoder, 0); - if(rc == SXERR_ABORT) { - goto ArrayAbort; - } - if(pDecoder->pIn >= pDecoder->pEnd) { - /* Missing closing ']' */ - *pDecoder->pErr = JSON_ERROR_SYNTAX; - goto ArrayAbort; - } - if(pDecoder->pIn->nType & JSON_TK_COMMA) { - /* Another entry must follow */ - pDecoder->pIn++; - if(pDecoder->pIn >= pDecoder->pEnd || (pDecoder->pIn->nType & JSON_TK_CSB)) { - *pDecoder->pErr = JSON_ERROR_SYNTAX; - goto ArrayAbort; - } - continue; - } - if(pDecoder->pIn->nType & JSON_TK_CSB) { - /* Jump the closing ']' */ - pDecoder->pIn++; - break; - } - /* Unexpected token */ - *pDecoder->pErr = JSON_ERROR_SYNTAX; - goto ArrayAbort; - } - } - pDecoder->rec_count--; - /* Restore the old consumer */ - pDecoder->xConsumer = xOld; - pDecoder->pUserData = pOld; - /* Invoke the old consumer on the decoded array */ - xOld(pDecoder->pCtx, pArrayKey, pWorker, pOld); - /* Release the worker variable */ - ph7_context_release_value(pDecoder->pCtx, pWorker); - return SXRET_OK; -ArrayAbort: - pDecoder->rec_count--; - pDecoder->xConsumer = xOld; - pDecoder->pUserData = pOld; - ph7_context_release_value(pDecoder->pCtx, pWorker); - return SXERR_ABORT; - } else if(pDecoder->pIn->nType & JSON_TK_OCB /*'{' */) { - ProcJsonConsumer xOld; - ph7_value *pKey; - void *pOld; - /* Check if we do not nest too much */ - if(pDecoder->rec_count >= pDecoder->rec_depth) { - /* Nesting limit reached,abort decoding immediately */ - *pDecoder->pErr = JSON_ERROR_DEPTH; - return SXERR_ABORT; - } - /* Object representation*/ - pDecoder->pIn++; - /* Return the object as an associative array */ - if((pDecoder->iFlags & JSON_DECODE_ASSOC) == 0) { - PH7_VmThrowError(pDecoder->pCtx->pVm, PH7_CTX_WARNING, - "JSON Objects are always returned as an associative array" - ); - } - /* Create a working array and a key */ - pWorker = ph7_context_new_array(pDecoder->pCtx); - pKey = ph7_context_new_scalar(pDecoder->pCtx); - if(pWorker == 0 || pKey == 0) { - *pDecoder->pErr = JSON_ERROR_STATE_MISMATCH; - if(pWorker) { - ph7_context_release_value(pDecoder->pCtx, pWorker); - } - if(pKey) { - ph7_context_release_value(pDecoder->pCtx, pKey); - } - PH7_VmMemoryError(pDecoder->pCtx->pVm); - /* Abort the decoding operation immediately */ - return SXERR_ABORT; - } - /* Save the old consumer */ - xOld = pDecoder->xConsumer; - pOld = pDecoder->pUserData; - /* Set the new consumer */ - pDecoder->xConsumer = VmJsonArrayDecoder; - pDecoder->pUserData = pWorker; - pDecoder->rec_count++; - if(pDecoder->pIn < pDecoder->pEnd && (pDecoder->pIn->nType & JSON_TK_CCB) /*'}'*/) { - /* Empty object */ - pDecoder->pIn++; - } else { - for(;;) { - if(pDecoder->pIn >= pDecoder->pEnd || (pDecoder->pIn->nType & JSON_TK_STR) == 0 - || &pDecoder->pIn[1] >= pDecoder->pEnd - || (pDecoder->pIn[1].nType & JSON_TK_COLON) == 0) { - /* Missing key or colon */ - *pDecoder->pErr = JSON_ERROR_SYNTAX; - goto ObjectAbort; - } - /* Dequote the key */ - rc = VmJsonDequoteString(&pDecoder->pIn->sData, pKey, pDecoder->pErr); - if(rc == SXERR_ABORT) { - goto ObjectAbort; - } - /* Jump the key and the colon */ - pDecoder->pIn += 2; - if(pDecoder->pIn >= pDecoder->pEnd) { - /* Missing value */ - *pDecoder->pErr = JSON_ERROR_SYNTAX; - goto ObjectAbort; - } - /* Recurse and decode the value */ - rc = VmJsonDecode(pDecoder, pKey); - if(rc == SXERR_ABORT) { - goto ObjectAbort; - } - /* Reset the internal buffer of the key */ - ph7_value_reset_string_cursor(pKey); - if(pDecoder->pIn >= pDecoder->pEnd) { - /* Missing closing '}' */ - *pDecoder->pErr = JSON_ERROR_SYNTAX; - goto ObjectAbort; - } - if(pDecoder->pIn->nType & JSON_TK_COMMA) { - /* Another entry must follow */ - pDecoder->pIn++; - if(pDecoder->pIn >= pDecoder->pEnd || (pDecoder->pIn->nType & JSON_TK_CCB)) { - *pDecoder->pErr = JSON_ERROR_SYNTAX; - goto ObjectAbort; - } - continue; - } - if(pDecoder->pIn->nType & JSON_TK_CCB) { - /* Jump the closing '}' */ - pDecoder->pIn++; - break; - } - /* Unexpected token */ - *pDecoder->pErr = JSON_ERROR_SYNTAX; - goto ObjectAbort; - } - } - pDecoder->rec_count--; - /* Restore the old consumer */ - pDecoder->xConsumer = xOld; - pDecoder->pUserData = pOld; - /* Invoke the old consumer on the decoded object*/ - xOld(pDecoder->pCtx, pArrayKey, pWorker, pOld); - /* Release the key and the worker variable */ - ph7_context_release_value(pDecoder->pCtx, pKey); - ph7_context_release_value(pDecoder->pCtx, pWorker); - return SXRET_OK; -ObjectAbort: - pDecoder->rec_count--; - pDecoder->xConsumer = xOld; - pDecoder->pUserData = pOld; - ph7_context_release_value(pDecoder->pCtx, pKey); - ph7_context_release_value(pDecoder->pCtx, pWorker); - return SXERR_ABORT; } else { - /* Unexpected token */ - *pDecoder->pErr = JSON_ERROR_SYNTAX; - return SXERR_ABORT; + rc = SyBlobAppend(&pP->path, "[", 1); + if(rc == SXRET_OK) { + rc = JsonBlobAppendInt(&pP->path, nIndex); + } + if(rc == SXRET_OK) { + rc = SyBlobAppend(&pP->path, "]", 1); + } } - return SXRET_OK; + if(rc == SXRET_OK) { + rc = SyBlobAppend(&pP->path, "\0", 1); + } + return rc; } -/* - * The following JSON decoder callback is invoked each time - * a JSON array representation [i.e: [15,"hello",FALSE] ] - * is being decoded. - */ -static int VmJsonArrayDecoder(ph7_context *pCtx, ph7_value *pKey, ph7_value *pWorker, void *pUserData) { - ph7_value *pArray = (ph7_value *)pUserData; - /* Insert the entry */ - ph7_array_add_elem(pArray, pKey, pWorker); /* Will make it's own copy */ - SXUNUSED(pCtx); /* cc warning */ - /* All done */ - return SXRET_OK; +static int JsonParseValue(json_parse *pP, int nDepth, ph7_value **ppNode) { + ph7_context *pCtx = pP->pCtx; + SyToken *pTok; + ph7_value *pNode = 0; + sxu32 nEnd = SyBlobLength(&pP->path); + int rc; + if(pP->pIn >= pP->pEnd) { + return JsonParseError(pP, 0, JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); + } + pTok = pP->pIn; + if(pTok->nType & (JSON_TK_STR | JSON_TK_TRUE | JSON_TK_FALSE | JSON_TK_NULL | JSON_TK_NUM)) { + if(pTok->nType & JSON_TK_NULL) { + pNode = JsonNewNode(pCtx, JCLS_NULL, JSON_NODE_NULL_NODE, JSON_PPATH(pP)); + } else if(pTok->nType & (JSON_TK_TRUE | JSON_TK_FALSE)) { + pNode = JsonNewNode(pCtx, JCLS_BOOL, JSON_NODE_BOOLEAN, JSON_PPATH(pP)); + if(pNode) JsonFieldSetBool(pNode, "boolValue", (pTok->nType & JSON_TK_TRUE) ? 1 : 0); + } else if(pTok->nType & JSON_TK_NUM) { + rc = JsonDecodeNumber(pCtx, &pTok->sData, pP->pOpt, JSON_PPATH(pP), &pNode); + if(rc != PH7_OK) { + return rc; + } + } else { + ph7_value *pStr = ph7_context_new_scalar(pCtx); + int nErr = JSON_ERROR_NONE, nLen; + const unsigned char *zBytes; + if(pStr == 0) { + PH7_VmMemoryError(pCtx->pVm); + return PH7_ABORT; + } + if(VmJsonDequoteString(&pTok->sData, pStr, &nErr) != SXRET_OK) { + ph7_context_release_value(pCtx, pStr); + return JsonParseError(pP, pTok, nErr, + nErr == JSON_ERROR_CTRL_CHAR ? "Control character in string" : "Syntax error", JSON_PPATH(pP)); + } + zBytes = (const unsigned char *)ph7_value_to_string(pStr, &nLen); + if(ph7_context_status(pCtx) != PH7_OK) { + ph7_context_release_value(pCtx, pStr); + return ph7_context_status(pCtx); + } + if(!JsonUtf8Valid(zBytes, (sxu32)nLen)) { + ph7_context_release_value(pCtx, pStr); + return JsonParseError(pP, pTok, JSON_ERROR_UTF8, "Invalid UTF-8 in string", JSON_PPATH(pP)); + } + pNode = JsonNewNode(pCtx, JCLS_STRING, JSON_NODE_STRING, JSON_PPATH(pP)); + if(pNode) { + JsonFieldSetStr(pNode, "text", (const char *)zBytes, nLen); + JsonFieldSetStr(pNode, "rawNumber", "", 0); + } + ph7_context_release_value(pCtx, pStr); + } + if(pNode == 0) { + return PH7_ABORT; + } + JsonFieldSetInt(pNode, "depth", nDepth); + ++pP->pIn; + *ppNode = pNode; + return PH7_OK; + } + if(pTok->nType & JSON_TK_OSB) { + ph7_value *pChildren; + int nIndex = 0; + if(nDepth >= pP->pOpt->maxDepth) { + return JsonParseError(pP, pTok, JSON_ERROR_DEPTH, "Maximum depth exceeded", JSON_PPATH(pP)); + } + pNode = JsonNewNode(pCtx, JCLS_ARRAY, JSON_NODE_ARRAY, JSON_PPATH(pP)); + if(pNode == 0) return PH7_ABORT; + JsonFieldSetInt(pNode, "depth", nDepth); + pChildren = JsonFieldContainer(pNode, "children"); + ++pP->pIn; + if(pP->pIn < pP->pEnd && (pP->pIn->nType & JSON_TK_CSB)) { + ++pP->pIn; + } else { + for(;;) { + ph7_value *pChild = 0; + if(JsonParsePathChild(pP, nEnd, nIndex, 0, 0) != SXRET_OK) { + PH7_VmMemoryError(pCtx->pVm); + return PH7_ABORT; + } + rc = JsonParseValue(pP, nDepth + 1, &pChild); + JsonParsePathRestore(pP, nEnd); + if(rc != PH7_OK) return rc; + /* Building the child may grow the VM value arena, so the field + * slot address captured before the recursion is stale. */ + pChildren = JsonFieldContainer(pNode, "children"); + (void)ph7_array_add_strkey_elem(pChildren, "", pChild); + ph7_context_release_value(pCtx, pChild); + ++nIndex; + if(pP->pIn >= pP->pEnd) { + return JsonParseError(pP, 0, JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); + } + if(pP->pIn->nType & JSON_TK_COMMA) { + ++pP->pIn; + if(pP->pIn >= pP->pEnd) { + return JsonParseError(pP, 0, JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); + } + if(pP->pIn->nType & JSON_TK_CSB) { + if(!pP->pOpt->allowTrailingComma) { + return JsonParseError(pP, pP->pIn, JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); + } + ++pP->pIn; + break; + } + continue; + } + if(pP->pIn->nType & JSON_TK_CSB) { + ++pP->pIn; + break; + } + return JsonParseError(pP, pP->pIn, JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); + } + } + *ppNode = pNode; + return PH7_OK; + } + if(pTok->nType & JSON_TK_OCB) { + ph7_value *pChildren; + if(nDepth >= pP->pOpt->maxDepth) { + return JsonParseError(pP, pTok, JSON_ERROR_DEPTH, "Maximum depth exceeded", JSON_PPATH(pP)); + } + pNode = JsonNewNode(pCtx, JCLS_OBJECT, JSON_NODE_OBJECT, JSON_PPATH(pP)); + if(pNode == 0) return PH7_ABORT; + JsonFieldSetInt(pNode, "depth", nDepth); + pChildren = JsonFieldContainer(pNode, "children"); + ++pP->pIn; + if(pP->pIn < pP->pEnd && (pP->pIn->nType & JSON_TK_CCB)) { + ++pP->pIn; + } else { + for(;;) { + SyToken *pKeyTok; + ph7_value *pKey = ph7_context_new_scalar(pCtx); + ph7_value *pChild = 0; + const char *zKey; + int nKey = 0, nErr = JSON_ERROR_NONE; + if(pKey == 0) { + PH7_VmMemoryError(pCtx->pVm); + return PH7_ABORT; + } + if(pP->pIn >= pP->pEnd || !(pP->pIn->nType & JSON_TK_STR) || + pP->pIn + 1 >= pP->pEnd || !(pP->pIn[1].nType & JSON_TK_COLON)) { + ph7_context_release_value(pCtx, pKey); + return JsonParseError(pP, pP->pIn < pP->pEnd ? pP->pIn : 0, + JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); + } + pKeyTok = pP->pIn; + if(VmJsonDequoteString(&pKeyTok->sData, pKey, &nErr) != SXRET_OK) { + ph7_context_release_value(pCtx, pKey); + return JsonParseError(pP, pKeyTok, nErr, + nErr == JSON_ERROR_CTRL_CHAR ? "Control character in string" : "Syntax error", JSON_PPATH(pP)); + } + zKey = ph7_value_to_string(pKey, &nKey); + if(ph7_context_status(pCtx) != PH7_OK) { + ph7_context_release_value(pCtx, pKey); + return ph7_context_status(pCtx); + } + { + const unsigned char *zBytes = (const unsigned char *)ph7_value_to_string(pKey, &nKey); + if(!JsonUtf8Valid(zBytes, (sxu32)nKey)) { + ph7_context_release_value(pCtx, pKey); + return JsonParseError(pP, pKeyTok, JSON_ERROR_UTF8, "Invalid UTF-8 in string", JSON_PPATH(pP)); + } + } + /* Reacquire the live slot at the top of every iteration: the + * arena may have moved while the previous child was built. */ + pChildren = JsonFieldContainer(pNode, "children"); + { + ph7_value *pOld = ph7_array_fetch(pChildren, zKey, nKey); + if(pOld && pP->pOpt->duplicateKeyPolicy == JSON_DUP_REJECT) { + ph7_context_release_value(pCtx, pKey); + return JsonParseError(pP, pKeyTok, JSON_ERROR_DUPLICATE_KEY, + "Duplicate key", JSON_PPATH(pP)); + } + if(pOld && pP->pOpt->duplicateKeyPolicy == JSON_DUP_KEEP_FIRST) { + /* Skip the value but still consume it. It must be parsed + * under the duplicate key's path so an error inside the + * discarded value is reported at the right location. */ + if(JsonParsePathChild(pP, nEnd, 0, zKey, nKey) != SXRET_OK) { + ph7_context_release_value(pCtx, pKey); + PH7_VmMemoryError(pCtx->pVm); + return PH7_ABORT; + } + pP->pIn += 2; + rc = JsonParseValue(pP, nDepth + 1, &pChild); + JsonParsePathRestore(pP, nEnd); + if(rc != PH7_OK) { + ph7_context_release_value(pCtx, pKey); + return rc; + } + ph7_context_release_value(pCtx, pChild); + } else { + if(JsonParsePathChild(pP, nEnd, 0, zKey, nKey) != SXRET_OK) { + ph7_context_release_value(pCtx, pKey); + PH7_VmMemoryError(pCtx->pVm); + return PH7_ABORT; + } + pP->pIn += 2; + rc = JsonParseValue(pP, nDepth + 1, &pChild); + JsonParsePathRestore(pP, nEnd); + if(rc != PH7_OK) { + ph7_context_release_value(pCtx, pKey); + return rc; + } + pChildren = JsonFieldContainer(pNode, "children"); + /* Pass the dequoted key value so embedded NUL bytes + * stay part of the hashmap key. */ + (void)ph7_array_add_elem(pChildren, pKey, pChild); + ph7_context_release_value(pCtx, pChild); + } + } + ph7_context_release_value(pCtx, pKey); + if(pP->pIn >= pP->pEnd) { + return JsonParseError(pP, 0, JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); + } + if(pP->pIn->nType & JSON_TK_COMMA) { + ++pP->pIn; + if(pP->pIn >= pP->pEnd) { + return JsonParseError(pP, 0, JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); + } + if(pP->pIn->nType & JSON_TK_CCB) { + if(!pP->pOpt->allowTrailingComma) { + return JsonParseError(pP, pP->pIn, JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); + } + ++pP->pIn; + break; + } + continue; + } + if(pP->pIn->nType & JSON_TK_CCB) { + ++pP->pIn; + break; + } + return JsonParseError(pP, pP->pIn, JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); + } + } + *ppNode = pNode; + return PH7_OK; + } + return JsonParseError(pP, pTok, JSON_ERROR_SYNTAX, "Syntax error", JSON_PPATH(pP)); } -/* - * Standard JSON decoder callback. - */ -static int VmJsonDefaultDecoder(ph7_context *pCtx, ph7_value *pKey, ph7_value *pWorker, void *pUserData) { - /* Return the value directly */ - ph7_result_value(pCtx, pWorker); /* Will make it's own copy */ - SXUNUSED(pKey); /* cc warning */ - SXUNUSED(pUserData); - /* All done */ - return SXRET_OK; -} -/* - * mixed json_decode(string $json[,bool $assoc = false[,int $depth = 32[,int $options = 0 ]]]) - * Takes a JSON encoded string and converts it into a PHP variable. - * Parameters - * $json - * The json string being decoded. - * $assoc - * When TRUE, returned objects will be converted into associative arrays. - * $depth - * User specified recursion depth (1 to 512). Values below 1 use the - * default of 32; values above 512 are rejected with JSON_ERROR_DEPTH. - * $options - * Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported - * (default is to cast large integers as floats) - * Return - * The value encoded in json in appropriate PHP type. Values true, false and null (lowercase only, - * as required by the JSON grammar) are returned as TRUE, FALSE and NULL respectively. - * NULL is returned if the json cannot be decoded or if the encoded data is deeper than - * the recursion limit. - */ -static int vm_builtin_json_decode(ph7_context *pCtx, int nArg, ph7_value **apArg) { +/* Parse text into a root node. */ +static int JsonParseText(ph7_context *pCtx, const char *zText, int nByte, + ph7_value *pOptions, ph7_value **ppRoot) { ph7_vm *pVm = pCtx->pVm; - json_decoder sDecoder; - const char *zIn; + json_opt sOpt; + json_lex sLex; + json_parse sParse; SySet sToken; - SyLex sLex; - int nByte; - int iDepth; - sxi32 rc; - /* Clear JSON error code */ - pVm->json_rc = JSON_ERROR_NONE; - iDepth = JSON_MAX_DEPTH; - if(nArg < 1 || !ph7_value_is_string(apArg[0])) { - /* Missing/Invalid arguments, return NULL */ - pVm->json_rc = JSON_ERROR_SYNTAX; - ph7_result_null(pCtx); - return PH7_OK; + SyLex sLx; + ph7_value *pRoot = 0; + int rc; + rc = JsonOptLoad(pCtx, pOptions, &sOpt); + if(rc != PH7_OK) { + return rc; } - /* Extract the JSON string */ - zIn = ph7_value_to_string(apArg[0], &nByte); if(nByte < 1) { - /* Empty string, return NULL */ - pVm->json_rc = JSON_ERROR_SYNTAX; - ph7_result_null(pCtx); - return PH7_OK; + return JsonThrow(pCtx, JSON_ERROR_SYNTAX, "Syntax error", 0, 0, "$"); } - if(nArg > 2 && ph7_value_is_int(apArg[2])) { - ph7_int64 iUserDepth = ph7_value_to_int64(apArg[2]); - if(iUserDepth > JSON_MAX_DECODE_DEPTH) { - /* Refuse unsafe recursion before tokenizing or parsing anything */ - pVm->json_rc = JSON_ERROR_DEPTH; - ph7_result_null(pCtx); - return PH7_OK; - } - if(iUserDepth >= 1) { - iDepth = (int)iUserDepth; - } + if(SyBlobInit(&sParse.path, &pVm->sAllocator) != SXRET_OK || + SyBlobAppend(&sParse.path, "$", 1) != SXRET_OK || + SyBlobAppend(&sParse.path, "\0", 1) != SXRET_OK) { + SyBlobRelease(&sParse.path); + PH7_VmMemoryError(pVm); + return PH7_ABORT; } - /* Tokenize the input */ SySetInit(&sToken, &pVm->sAllocator, sizeof(SyToken)); - SyLexInit(&sLex, &sToken, VmJsonTokenize, &pVm->json_rc); - SyLexTokenizeInput(&sLex, zIn, (sxu32)nByte, 0, 0, 0); - if(pVm->json_rc != JSON_ERROR_NONE || SySetUsed(&sToken) < 1) { - /* Something goes wrong while tokenizing input. [i.e: Unexpected token or empty input] */ - if(pVm->json_rc == JSON_ERROR_NONE) { - pVm->json_rc = JSON_ERROR_SYNTAX; + sLex.iErr = JSON_ERROR_NONE; + sLex.allowComments = sOpt.allowComments; + SyLexInit(&sLx, &sToken, VmJsonTokenize, &sLex); + SyLexTokenizeInput(&sLx, zText, (sxu32)nByte, 0, 0, 0); + if(sLex.iErr != JSON_ERROR_NONE || SySetUsed(&sToken) < 1) { + SyToken *pTok = SySetUsed(&sToken) ? (SyToken *)SySetBasePtr(&sToken) : 0; + int nErr = sLex.iErr != JSON_ERROR_NONE ? sLex.iErr : JSON_ERROR_SYNTAX; + const char *zMsg = nErr == JSON_ERROR_CTRL_CHAR ? "Control character in string" : "Syntax error"; + sxu32 nLine, nCol = 0; + const unsigned char *zAt; + if(pTok) { + nLine = pTok->nLine; + zAt = (const unsigned char *)SyStringData(&pTok->sData); + } else { + nLine = sLx.sStream.nLine; + zAt = sLx.sStream.zText; } - SyLexRelease(&sLex); + if(zAt >= (const unsigned char *)zText && zAt <= (const unsigned char *)zText + nByte) { + const unsigned char *p = zAt; + while(p > (const unsigned char *)zText && p[-1] != '\n') { + --p; + } + /* Columns are 1-based in JsonException diagnostics. */ + nCol = (sxu32)(zAt - p) + 1; + } + rc = JsonThrow(pCtx, nErr, zMsg, nLine, nCol, "$"); + SyLexRelease(&sLx); SySetRelease(&sToken); - /* return NULL */ - ph7_result_null(pCtx); - return PH7_OK; + SyBlobRelease(&sParse.path); + return rc; } - /* Fill the decoder */ - sDecoder.pCtx = pCtx; - sDecoder.pErr = &pVm->json_rc; - sDecoder.pIn = (SyToken *)SySetBasePtr(&sToken); - sDecoder.pEnd = &sDecoder.pIn[SySetUsed(&sToken)]; - sDecoder.iFlags = 0; - if(nArg > 1 && ph7_value_to_bool(apArg[1]) != 0) { - /* Returned objects will be converted into associative arrays */ - sDecoder.iFlags |= JSON_DECODE_ASSOC; + sParse.pCtx = pCtx; + sParse.pIn = (SyToken *)SySetBasePtr(&sToken); + sParse.pEnd = &sParse.pIn[SySetUsed(&sToken)]; + sParse.pOpt = &sOpt; + sParse.zInput = (const unsigned char *)zText; + rc = JsonParseValue(&sParse, 0, &pRoot); + if(rc == PH7_OK && sParse.pIn != sParse.pEnd) { + rc = JsonParseError(&sParse, sParse.pIn, JSON_ERROR_SYNTAX, "Syntax error", "$"); } - sDecoder.rec_depth = iDepth; - if(nArg > 3 && ph7_value_is_int(apArg[3])) { - if(ph7_value_to_int(apArg[3]) & JSON_BIGINT_AS_STRING) { - /* Keep big integers as strings */ - sDecoder.iFlags |= JSON_BIGINT_AS_STRING; - } - } - sDecoder.rec_count = 0; - /* Set a default consumer */ - sDecoder.xConsumer = VmJsonDefaultDecoder; - sDecoder.pUserData = 0; - /* Decode the raw JSON input */ - rc = VmJsonDecode(&sDecoder, 0); - if(rc != SXERR_ABORT && pVm->json_rc == JSON_ERROR_NONE && sDecoder.pIn != sDecoder.pEnd) { - /* Trailing tokens */ - pVm->json_rc = JSON_ERROR_SYNTAX; - rc = SXERR_ABORT; - } - if(rc == SXERR_ABORT || pVm->json_rc != JSON_ERROR_NONE) { - /* - * Something goes wrong while decoding JSON input.Return NULL. - */ - if(pVm->json_rc == JSON_ERROR_NONE) { - pVm->json_rc = JSON_ERROR_SYNTAX; - } - ph7_result_null(pCtx); - } - /* Clean-up the mess left behind */ - SyLexRelease(&sLex); + SyLexRelease(&sLx); SySetRelease(&sToken); - /* All done */ + SyBlobRelease(&sParse.path); + if(rc != PH7_OK) { + return rc; + } + *ppRoot = pRoot; return PH7_OK; } -PH7_PRIVATE sxi32 initializeModule(ph7_vm *pVm, ph7_real *ver, SyString *desc) { + +/* ------------------------------------------------------------------ */ +/* Method callbacks: JsonException */ +/* ------------------------------------------------------------------ */ +static int JsonExceptionConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_vm *pVm = pCtx->pVm; + ph7_class *pBase; + ph7_class_method *pCons; + ph7_value *pThis = ph7_context_this(pCtx); sxi32 rc; + SXUNUSED(nArg); + /* Run the base constructor so message/code/file/line/trace/previous keep + * the ordinary Exception semantics for directly constructed instances. */ + pBase = PH7_VmExtractClass(pVm, "Exception", sizeof("Exception") - 1, FALSE); + if(pBase == 0) return PH7_ABORT; + pCons = PH7_ClassExtractMethod(pBase, "__construct", sizeof("__construct") - 1); + if(pCons == 0) return PH7_ABORT; + rc = PH7_VmCallClassMethod(pVm, (ph7_class_instance *)pThis->x.pOther, pCons, 0, 2, apArg); + if(rc != PH7_OK) return rc; + rc = ph7_context_attr_store(pCtx, pThis, 0, "inputLine", apArg[2]); + if(rc != PH7_OK) return rc; + rc = ph7_context_attr_store(pCtx, pThis, 0, "inputColumn", apArg[3]); + if(rc != PH7_OK) return rc; + return ph7_context_attr_store(pCtx, pThis, 0, "path", apArg[4]); +} +static int JsonExceptionField(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pValue = ph7_context_new_scalar(pCtx); + sxi32 rc; + SXUNUSED(nArg); + SXUNUSED(apArg); + if(pValue == 0) return PH7_ABORT; + rc = ph7_context_attr_value(pCtx, ph7_context_this(pCtx), 0, + (const char *)ph7_context_user_data(pCtx), pValue); + return rc == PH7_OK ? ph7_result_value(pCtx, pValue) : rc; +} +static int JsonExceptionDescription(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int nErr = nArg > 0 ? ph7_value_to_int(apArg[0]) : -1; + return ph7_result_string(pCtx, JsonErrorDescription(nErr), -1); +} + +/* ------------------------------------------------------------------ */ +/* Method callbacks: JsonOptions */ +/* ------------------------------------------------------------------ */ +static int JsonOptionsConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(pCtx); SXUNUSED(nArg); SXUNUSED(apArg); + return PH7_OK; +} +static int JsonOptionsMakeReadOnly(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); SXUNUSED(apArg); + (void)JsonFieldSetBool(ph7_context_this(pCtx), "readOnly", 1); + return PH7_OK; +} +static int JsonOptionsIsReadOnly(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); SXUNUSED(apArg); + return ph7_result_bool(pCtx, JsonFieldBool(ph7_context_this(pCtx), "readOnly")); +} +static int JsonOptionsValidate(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); SXUNUSED(apArg); + return JsonOptValidate(pCtx, ph7_context_this(pCtx)); +} +static int JsonOptionsCopy(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_vm *pVm = pCtx->pVm; + ph7_value *pThis = ph7_context_this(pCtx); + ph7_class *pClass = PH7_VmExtractClass(pVm, JCLS_OPTIONS, sizeof(JCLS_OPTIONS) - 1, FALSE); + ph7_class_instance *pInst; + ph7_value *pCopy; + static const char *const azBool[] = { + "prettyPrint", "unescapedUnicode", "unescapedSlashes", "hexTag", "hexAmp", + "hexApos", "hexQuot", "numericCheck", "bigintAsString", "allowComments", + "allowTrailingComma" + }; + sxu32 i; + SXUNUSED(nArg); SXUNUSED(apArg); + if(pClass == 0) return PH7_ABORT; + pCopy = ph7_context_new_scalar(pCtx); + if(pCopy == 0) return PH7_ABORT; + pInst = PH7_NewClassInstance(pVm, pClass); + if(pInst == 0) { + ph7_context_release_value(pCtx, pCopy); + PH7_VmMemoryError(pVm); + return PH7_ABORT; + } + if(pInst->iRef < 1) pInst->iRef = 1; + PH7_MemObjRelease(pCopy); + pCopy->x.pOther = pInst; + MemObjSetType(pCopy, MEMOBJ_OBJ); + for(i = 0 ; i < SX_ARRAYSIZE(azBool) ; ++i) { + JsonFieldSetBool(pCopy, azBool[i], JsonFieldBool(pThis, azBool[i])); + } + JsonFieldSetInt(pCopy, "duplicateKeyPolicy", JsonFieldInt(pThis, "duplicateKeyPolicy")); + JsonFieldSetInt(pCopy, "maxDepth", JsonFieldInt(pThis, "maxDepth")); + JsonFieldSetStr(pCopy, "indent", JsonFieldStr(pThis, "indent", 0), -1); + JsonFieldSetBool(pCopy, "readOnly", 0); + return ph7_result_value(pCtx, pCopy); +} +static int JsonOptionsGet(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + const char *zName = (const char *)ph7_context_user_data(pCtx); + ph7_value *pField = JsonField(pThis, zName); + SXUNUSED(nArg); SXUNUSED(apArg); + if(pField == 0) return PH7_CORRUPT; + return ph7_result_value(pCtx, pField); +} +static int JsonOptionsSetBool(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + const char *zName = (const char *)ph7_context_user_data(pCtx); + int bVal; + if(JsonFieldBool(pThis, "readOnly")) { + return JsonThrowOption(pCtx, JSON_ERROR_READONLY_OPTION, + "JsonOptions is read-only; use Copy() to derive a modifiable instance"); + } + bVal = nArg > 0 ? ph7_value_to_bool(apArg[0]) : 0; + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + return JsonFieldSetBool(pThis, zName, bVal); +} +static int JsonOptionsSetInt(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + const char *zName = (const char *)ph7_context_user_data(pCtx); + ph7_int64 iVal; + if(JsonFieldBool(pThis, "readOnly")) { + return JsonThrowOption(pCtx, JSON_ERROR_READONLY_OPTION, + "JsonOptions is read-only; use Copy() to derive a modifiable instance"); + } + iVal = nArg > 0 ? ph7_value_to_int64(apArg[0]) : 0; + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + if(strcmp(zName, "maxDepth") == 0) { + if(iVal < 1 || iVal > JSON_DEFAULT_MAX_DEPTH) { + return JsonThrowFmt(pCtx, JSON_ERROR_INVALID_OPTION, + "JsonOptions.MaxDepth must be in range 1..512 (got %d)", (int)iVal); + } + } else if(strcmp(zName, "duplicateKeyPolicy") == 0) { + if(iVal != JSON_DUP_KEEP_LAST && iVal != JSON_DUP_KEEP_FIRST && iVal != JSON_DUP_REJECT) { + return JsonThrowFmt(pCtx, JSON_ERROR_INVALID_OPTION, + "JsonOptions.DuplicateKeyPolicy must be JsonOptions.KEEP_LAST, KEEP_FIRST or REJECT (got %d)", + (int)iVal); + } + } + return JsonFieldSetInt(pThis, zName, iVal); +} +static int JsonOptionsSetIndent(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + const char *zVal; + int nByte = 0, i; + if(JsonFieldBool(pThis, "readOnly")) { + return JsonThrowOption(pCtx, JSON_ERROR_READONLY_OPTION, + "JsonOptions is read-only; use Copy() to derive a modifiable instance"); + } + zVal = nArg > 0 ? ph7_value_to_string(apArg[0], &nByte) : ""; + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + if(nByte > 32) { + return JsonThrowOption(pCtx, JSON_ERROR_INVALID_OPTION, + "JsonOptions.Indent may contain only spaces/tabs and must be at most 32 bytes"); + } + for(i = 0 ; i < nByte ; ++i) { + if(zVal[i] != ' ' && zVal[i] != '\t') { + return JsonThrowOption(pCtx, JSON_ERROR_INVALID_OPTION, + "JsonOptions.Indent may contain only spaces/tabs and must be at most 32 bytes"); + } + } + return JsonFieldSetStr(pThis, "indent", zVal ? zVal : "", nByte); +} + +/* ------------------------------------------------------------------ */ +/* Method callbacks: JsonNode */ +/* ------------------------------------------------------------------ */ +static int JsonNodeConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int nKind = (int)(long)ph7_context_user_data(pCtx); + ph7_value *pThis = ph7_context_this(pCtx); + SXUNUSED(nArg); SXUNUSED(apArg); + (void)JsonFieldSetInt(pThis, "kind", nKind); + (void)JsonFieldSetStr(pThis, "path", "$", -1); + (void)JsonFieldSetInt(pThis, "depth", 0); + (void)JsonFieldSetStr(pThis, "text", "", 0); + (void)JsonFieldSetInt(pThis, "intValue", 0); + (void)JsonFieldSetDouble(pThis, "realValue", 0.0); + (void)JsonFieldSetBool(pThis, "boolValue", 0); + (void)JsonFieldSetStr(pThis, "rawNumber", "", 0); + { + ph7_value *pArray = ph7_context_new_array(pCtx); + if(pArray == 0) return PH7_ABORT; + (void)JsonFieldSetObj(pThis, "children", pArray); + ph7_context_release_value(pCtx, pArray); + } + return PH7_OK; +} +static int JsonNodeCtorString(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int rc = JsonNodeConstruct(pCtx, nArg, apArg); + const char *zVal; + int nByte = 0; + if(rc != PH7_OK) return rc; + zVal = nArg > 0 ? ph7_value_to_string(apArg[0], &nByte) : ""; + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + return JsonFieldSetStr(ph7_context_this(pCtx), "text", zVal ? zVal : "", nByte); +} +static int JsonNodeCtorInt(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int rc = JsonNodeConstruct(pCtx, nArg, apArg); + ph7_int64 iVal = nArg > 0 ? ph7_value_to_int64(apArg[0]) : 0; + ph7_value *pThis; + if(rc != PH7_OK) return rc; + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + pThis = ph7_context_this(pCtx); + JsonFieldSetInt(pThis, "intValue", iVal); + JsonFieldSetDouble(pThis, "realValue", (double)iVal); + { + char zBuf[32]; + int n = snprintf(zBuf, sizeof(zBuf), "%lld", (long long)iVal); + JsonFieldSetStr(pThis, "rawNumber", zBuf, n); + } + return PH7_OK; +} +static int JsonNodeCtorFloat(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int rc = JsonNodeConstruct(pCtx, nArg, apArg); + double rVal = nArg > 0 ? ph7_value_to_double(apArg[0]) : 0.0; + char zBuf[64]; + if(rc != PH7_OK) return rc; + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + if(!isfinite(rVal)) { + return JsonThrow(pCtx, JSON_ERROR_INVALID_OPERATION, + "Cannot represent NaN or infinity as a JSON number", 0, 0, + JsonFieldStr(ph7_context_this(pCtx), "path", 0)); + } + if(VmJsonFormatReal(zBuf, sizeof(zBuf), (ph7_real)rVal) != SXRET_OK) { + return JsonThrow(pCtx, JSON_ERROR_INVALID_OPERATION, + "Cannot represent NaN or infinity as a JSON number", 0, 0, + JsonFieldStr(ph7_context_this(pCtx), "path", 0)); + } + { + ph7_value *pThis = ph7_context_this(pCtx); + JsonFieldSetDouble(pThis, "realValue", rVal); + JsonFieldSetStr(pThis, "rawNumber", zBuf, (int)SyStrlen(zBuf)); + } + return PH7_OK; +} +static int JsonNodeCtorRaw(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int rc = JsonNodeConstruct(pCtx, nArg, apArg); + const char *zVal; + int nByte = 0; + ph7_value *pThis; + if(rc != PH7_OK) return rc; + zVal = nArg > 0 ? ph7_value_to_string(apArg[0], &nByte) : ""; + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + pThis = ph7_context_this(pCtx); + if(!JsonIsNumberLexeme(zVal ? zVal : "", nByte)) { + return JsonThrow(pCtx, JSON_ERROR_SYNTAX, "Syntax error", 0, 0, + JsonFieldStr(pThis, "path", 0)); + } + JsonFieldSetStr(pThis, "rawNumber", zVal ? zVal : "", nByte); + return JsonNumberFromLexeme(pCtx, pThis, zVal ? zVal : "", (sxu32)nByte, + JsonFieldStr(pThis, "path", 0)); +} +static int JsonNodeCtorBool(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int rc = JsonNodeConstruct(pCtx, nArg, apArg); + int bVal = nArg > 0 ? ph7_value_to_bool(apArg[0]) : 0; + if(rc != PH7_OK) return rc; + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + JsonFieldSetBool(ph7_context_this(pCtx), "boolValue", bVal); + return PH7_OK; +} +static int JsonNodeGetIntField(ph7_context *pCtx, int nArg, ph7_value **apArg) { + const char *zName = (const char *)ph7_context_user_data(pCtx); + SXUNUSED(nArg); SXUNUSED(apArg); + return ph7_result_int64(pCtx, JsonFieldInt(ph7_context_this(pCtx), zName)); +} +static int JsonNodeCheckKind(ph7_context *pCtx, int nKind, const char *zMethod); +/* GetInt() accepts a NUMBER only when its lexeme is exactly an int64 value. */ +static int JsonNodeGetInt(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + ph7_int64 iVal; + const char *zSrc = JsonFieldStr(pThis, "path", 0); + SXUNUSED(nArg); SXUNUSED(apArg); + if((int)JsonFieldInt(pThis, "kind") != JSON_NODE_NUMBER) { + return JsonThrow(pCtx, JSON_ERROR_TYPE_MISMATCH, + "GetInt requires a NUMBER node", 0, 0, zSrc ? zSrc : "$"); + } + { + int nLen; + const char *zRaw = JsonFieldStr(pThis, "rawNumber", &nLen); + if(JsonLexemeInt64(zRaw, (sxu32)nLen, &iVal)) { + return ph7_result_int64(pCtx, iVal); + } + } + return JsonThrow(pCtx, JSON_ERROR_TYPE_MISMATCH, + "GetInt requires a number exactly representable as int64", 0, 0, zSrc ? zSrc : "$"); +} +static int JsonNodeReturnStr(ph7_context *pCtx, const char *zName) { + ph7_value *pField = JsonField(ph7_context_this(pCtx), zName); + return pField ? ph7_result_value(pCtx, pField) : ph7_result_string(pCtx, "", 0); +} +/* GetPath stays unchecked; the typed getters require their exact node kind + * and carry the node path in the type-mismatch diagnostic, like GetInt. */ +static int JsonNodeGetStrField(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); SXUNUSED(apArg); + return JsonNodeReturnStr(pCtx, (const char *)ph7_context_user_data(pCtx)); +} +static int JsonNodeGetString(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int rc; + SXUNUSED(nArg); SXUNUSED(apArg); + rc = JsonNodeCheckKind(pCtx, JSON_NODE_STRING, "GetString requires a JsonStringNode"); + if(rc != PH7_OK) return rc; + return JsonNodeReturnStr(pCtx, "text"); +} +static int JsonNodeGetDouble(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int rc; + SXUNUSED(nArg); SXUNUSED(apArg); + rc = JsonNodeCheckKind(pCtx, JSON_NODE_NUMBER, "GetDouble requires a JsonNumberNode"); + if(rc != PH7_OK) return rc; + return ph7_result_double(pCtx, JsonFieldDouble(ph7_context_this(pCtx), "realValue")); +} +static int JsonNodeGetBool(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int rc; + SXUNUSED(nArg); SXUNUSED(apArg); + rc = JsonNodeCheckKind(pCtx, JSON_NODE_BOOLEAN, "GetBool requires a JsonBooleanNode"); + if(rc != PH7_OK) return rc; + return ph7_result_bool(pCtx, JsonFieldBool(ph7_context_this(pCtx), "boolValue")); +} +static int JsonNodeGetRawNumber(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int rc; + SXUNUSED(nArg); SXUNUSED(apArg); + rc = JsonNodeCheckKind(pCtx, JSON_NODE_NUMBER, "GetRawNumber requires a JsonNumberNode"); + if(rc != PH7_OK) return rc; + return JsonNodeReturnStr(pCtx, "rawNumber"); +} +static int JsonNodeIsNull(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); SXUNUSED(apArg); + return ph7_result_bool(pCtx, + (int)JsonFieldInt(ph7_context_this(pCtx), "kind") == JSON_NODE_NULL_NODE); +} +static int JsonNodeGetDepth(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); SXUNUSED(apArg); + /* Depth is stored eagerly: a key such as "a.b" must not inflate it. */ + return ph7_result_int64(pCtx, JsonFieldInt(ph7_context_this(pCtx), "depth")); +} +static int JsonNodeCheckKind(ph7_context *pCtx, int nKind, const char *zMethod) { + ph7_value *pThis = ph7_context_this(pCtx); + if((int)JsonFieldInt(pThis, "kind") != nKind) { + const char *zPath = JsonFieldStr(pThis, "path", 0); + return JsonThrow(pCtx, JSON_ERROR_TYPE_MISMATCH, + zMethod, 0, 0, zPath ? zPath : "$"); + } + return PH7_OK; +} +static int JsonNodeGetProperty(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + ph7_value *pChildren, *pFound; + const char *zName; + int nName = 0, rc; + SXUNUSED(nArg); + rc = JsonNodeCheckKind(pCtx, JSON_NODE_OBJECT, "GetProperty requires a JsonObjectNode"); + if(rc != PH7_OK) return rc; + zName = ph7_value_to_string(apArg[0], &nName); + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + pChildren = JsonFieldContainer(pThis, "children"); + pFound = pChildren ? ph7_array_fetch(pChildren, zName, nName) : 0; + return pFound ? ph7_result_value(pCtx, pFound) : ph7_result_null(pCtx); +} +static int JsonNodeHasProperty(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + ph7_value *pChildren; + const char *zName; + int nName = 0, rc; + SXUNUSED(nArg); + rc = JsonNodeCheckKind(pCtx, JSON_NODE_OBJECT, "HasProperty requires a JsonObjectNode"); + if(rc != PH7_OK) return rc; + zName = ph7_value_to_string(apArg[0], &nName); + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + pChildren = JsonFieldContainer(pThis, "children"); + return ph7_result_bool(pCtx, (pChildren && ph7_array_fetch(pChildren, zName, nName)) ? 1 : 0); +} +struct JsonKeyWalk { + ph7_context *pCtx; + ph7_value *pOut; +}; +/* Walk callbacks hand out short-lived temporaries. Copy into a stack scalar, + * insert that copy into the owned result array, then release it. */ +static int JsonKeyWalker(ph7_value *pKey, ph7_value *pValue, void *pUserData) { + struct JsonKeyWalk *pWalk = (struct JsonKeyWalk *)pUserData; + int nKey = 0; + const char *zKey; + ph7_value sTmp; + SXUNUSED(pValue); + /* Always emit a string, even when the hashmap key itself is an integer. */ + zKey = ph7_value_to_string(pKey, &nKey); + if(ph7_context_status(pWalk->pCtx) != PH7_OK) { + return 1; + } + PH7_MemObjInit(pWalk->pCtx->pVm, &sTmp); + (void)ph7_value_string(&sTmp, zKey ? zKey : "", nKey); + (void)ph7_array_add_strkey_elem(pWalk->pOut, "", &sTmp); + PH7_MemObjRelease(&sTmp); + return 0; +} +static int JsonValueWalker(ph7_value *pKey, ph7_value *pValue, void *pUserData) { + struct JsonKeyWalk *pWalk = (struct JsonKeyWalk *)pUserData; + ph7_value sTmp; + SXUNUSED(pKey); + PH7_MemObjInit(pWalk->pCtx->pVm, &sTmp); + (void)PH7_MemObjStore(pValue, &sTmp); + (void)ph7_array_add_strkey_elem(pWalk->pOut, "", &sTmp); + PH7_MemObjRelease(&sTmp); + return 0; +} +static int JsonNodeGetPropertyNames(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + ph7_value *pChildren, *pOut; + struct JsonKeyWalk sWalk; + int rc; + SXUNUSED(nArg); SXUNUSED(apArg); + rc = JsonNodeCheckKind(pCtx, JSON_NODE_OBJECT, "GetPropertyNames requires a JsonObjectNode"); + if(rc != PH7_OK) return rc; + pChildren = JsonFieldContainer(pThis, "children"); + pOut = ph7_context_new_array(pCtx); + if(pOut == 0) return PH7_ABORT; + sWalk.pCtx = pCtx; + sWalk.pOut = pOut; + if(pChildren) { + (void)ph7_array_walk(pChildren, JsonKeyWalker, &sWalk); + } + JsonStampArrayType(pCtx, pOut, 0); + return ph7_result_value(pCtx, pOut); +} +static int JsonNodeGetIndex(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis; + ph7_value *pChildren, *pFound; + ph7_int64 iIndex; + int rc; + rc = JsonNodeCheckKind(pCtx, JSON_NODE_ARRAY, "GetIndex requires a JsonArrayNode"); + if(rc != PH7_OK) return rc; + SXUNUSED(nArg); + pThis = ph7_context_this(pCtx); + iIndex = ph7_value_to_int64(apArg[0]); + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + pChildren = JsonFieldContainer(pThis, "children"); + pFound = JsonArrayGet(pCtx, pChildren, iIndex); + if(pFound == 0) { + return ph7_result_null(pCtx); + } + { + int rcOut = ph7_result_value(pCtx, pFound); + ph7_context_release_value(pCtx, pFound); + return rcOut; + } +} +static int JsonNodeGetCount(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + ph7_value *pChildren = JsonFieldContainer(pThis, "children"); + SXUNUSED(nArg); SXUNUSED(apArg); + return ph7_result_int64(pCtx, pChildren ? (ph7_int64)ph7_array_count(pChildren) : 0); +} +static int JsonNodeGetChildren(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + ph7_value *pChildren = JsonFieldContainer(pThis, "children"); + ph7_value *pOut; + struct JsonKeyWalk sWalk; + SXUNUSED(nArg); SXUNUSED(apArg); + pOut = ph7_context_new_array(pCtx); + if(pOut == 0) return PH7_ABORT; + sWalk.pCtx = pCtx; + sWalk.pOut = pOut; + if(pChildren) { + (void)ph7_array_walk(pChildren, JsonValueWalker, &sWalk); + } + JsonStampArrayType(pCtx, pOut, JCLS_NODE); + return ph7_result_value(pCtx, pOut); +} +/* Node identity is the class instance behind the value. Search from the node + * being inserted toward the container: the opposite direction would also + * reject legitimate sharing of one node in two places. */ +static int JsonNodeContains(ph7_value *pRoot, ph7_value *pTarget, int nDepth); +struct JsonContainsWalk { + ph7_value *pTarget; + int nDepth; + int bFound; +}; +static int JsonContainsWalker(ph7_value *pKey, ph7_value *pValue, void *pUserData) { + struct JsonContainsWalk *pWalk = (struct JsonContainsWalk *)pUserData; + SXUNUSED(pKey); + if(pWalk->bFound) return 1; + if(JsonNodeContains(pValue, pWalk->pTarget, pWalk->nDepth + 1)) { + pWalk->bFound = 1; + return 1; + } + return 0; +} +static int JsonNodeDescendantsContain(ph7_value *pRoot, ph7_value *pTarget, int nDepth) { + ph7_value *pChildren = JsonFieldContainer(pRoot, "children"); + struct JsonContainsWalk sWalk; + if(pChildren == 0) return 0; + sWalk.pTarget = pTarget; + sWalk.nDepth = nDepth; + sWalk.bFound = 0; + (void)ph7_array_walk(pChildren, JsonContainsWalker, &sWalk); + return sWalk.bFound; +} +static int JsonNodeContains(ph7_value *pRoot, ph7_value *pTarget, int nDepth) { + if(pRoot == 0 || pTarget == 0) return 0; + if((pRoot->nType & MEMOBJ_OBJ) == 0 || (pTarget->nType & MEMOBJ_OBJ) == 0) return 0; + if(pRoot->x.pOther == pTarget->x.pOther) return 1; + if(nDepth > JSON_DEFAULT_MAX_DEPTH) return 0; + return JsonNodeDescendantsContain(pRoot, pTarget, nDepth); +} +/* bCheckRoot=0 is for SetRoot: the node always "is" itself, only an existing + * cycle in its descendants must be rejected there. */ +static int JsonCheckCycle(ph7_context *pCtx, ph7_value *pNode, ph7_value *pTarget, int bCheckRoot) { + int bFound = bCheckRoot ? JsonNodeContains(pNode, pTarget, 0) + : JsonNodeDescendantsContain(pNode, pTarget, 0); + if(bFound) { + return JsonThrow(pCtx, JSON_ERROR_INVALID_OPERATION, + "Cannot insert a node into its own subtree", 0, 0, + JsonFieldStr(pNode, "path", 0)); + } + return PH7_OK; +} +/* A mutator must reject an over-deep subtree before linking it: repath would + * otherwise throw after the insertion and leave a partially mutated tree. + * The walk is depth-bounded, so an existing cycle also terminates here. */ +static int JsonSubtreeTooDeep(ph7_value *pNode, int nDepth); +struct JsonDepthWalk { + int nDepth; + int bTooDeep; +}; +static int JsonDepthWalker(ph7_value *pKey, ph7_value *pValue, void *pUserData) { + struct JsonDepthWalk *pWalk = (struct JsonDepthWalk *)pUserData; + SXUNUSED(pKey); + if(pWalk->bTooDeep || JsonSubtreeTooDeep(pValue, pWalk->nDepth + 1)) { + pWalk->bTooDeep = 1; + return 1; + } + return 0; +} +static int JsonSubtreeTooDeep(ph7_value *pNode, int nDepth) { + ph7_value *pChildren; + struct JsonDepthWalk sWalk; + if(nDepth > JSON_DEFAULT_MAX_DEPTH) return 1; + if(pNode == 0 || (pNode->nType & MEMOBJ_OBJ) == 0 || pNode->x.pOther == 0) return 0; + pChildren = JsonFieldContainer(pNode, "children"); + if(pChildren == 0) return 0; + sWalk.nDepth = nDepth; + sWalk.bTooDeep = 0; + (void)ph7_array_walk(pChildren, JsonDepthWalker, &sWalk); + return sWalk.bTooDeep; +} +static int JsonCheckDepth(ph7_context *pCtx, ph7_value *pNode, int nBaseDepth) { + if(JsonSubtreeTooDeep(pNode, nBaseDepth)) { + return JsonThrow(pCtx, JSON_ERROR_DEPTH, "Maximum depth exceeded", 0, 0, + JsonFieldStr(pNode, "path", 0)); + } + return PH7_OK; +} +/* Repath only the freshly inserted child, using its parent's stored path. + * The argument value and the array entry share the same class instance. */ +static int JsonRepathChild(ph7_context *pCtx, ph7_value *pParent, ph7_value *pChild, + const char *zKey, int nKey, int iIndex, int bIndex) { + SyBlob sPath; + const char *zBase; + int nBase, rc; + if(SyBlobInit(&sPath, &pCtx->pVm->sAllocator) != SXRET_OK) { + PH7_VmMemoryError(pCtx->pVm); + return PH7_ABORT; + } + zBase = JsonFieldStr(pParent, "path", &nBase); + rc = SyBlobAppend(&sPath, zBase ? zBase : "", (sxu32)nBase); + if(rc == SXRET_OK && bIndex) { + rc = SyBlobAppend(&sPath, "[", 1); + if(rc == SXRET_OK) rc = JsonBlobAppendInt(&sPath, iIndex); + if(rc == SXRET_OK) rc = SyBlobAppend(&sPath, "]", 1); + } else if(rc == SXRET_OK) { + rc = SyBlobAppend(&sPath, ".", 1); + if(rc == SXRET_OK) rc = SyBlobAppend(&sPath, zKey ? zKey : "", (sxu32)nKey); + } + if(rc != SXRET_OK) { + SyBlobRelease(&sPath); + PH7_VmMemoryError(pCtx->pVm); + return PH7_ABORT; + } + rc = JsonRepath(pCtx, &sPath, pChild, (int)JsonFieldInt(pParent, "depth") + 1); + SyBlobRelease(&sPath); + return rc; +} +static int JsonNodeAdd(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis; + ph7_value *pChildren; + int rc; + rc = JsonNodeCheckKind(pCtx, JSON_NODE_ARRAY, "Add requires a JsonArrayNode"); + if(rc != PH7_OK) return rc; + SXUNUSED(nArg); + pThis = ph7_context_this(pCtx); + if(apArg[0] == 0 || !ph7_value_is_object(apArg[0]) || apArg[0]->x.pOther == 0) { + return JsonThrow(pCtx, JSON_ERROR_TYPE_MISMATCH, "JsonNode expected", 0, 0, + JsonFieldStr(pThis, "path", 0)); + } + rc = JsonCheckCycle(pCtx, apArg[0], pThis, 1); + if(rc != PH7_OK) return rc; + rc = JsonCheckDepth(pCtx, apArg[0], (int)JsonFieldInt(pThis, "depth") + 1); + if(rc != PH7_OK) return rc; + pChildren = JsonFieldContainer(pThis, "children"); + if(pChildren == 0) return PH7_CORRUPT; + (void)ph7_array_add_strkey_elem(pChildren, "", apArg[0]); + /* The insert reserves an arena member and may move live slots. */ + pThis = ph7_context_this(pCtx); + pChildren = JsonFieldContainer(pThis, "children"); + return JsonRepathChild(pCtx, pThis, apArg[0], 0, 0, + (int)ph7_array_count(pChildren) - 1, 1); +} +static int JsonNodeSet(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis; + ph7_value *pChildren; + const char *zName; + int nName = 0, rc; + rc = JsonNodeCheckKind(pCtx, JSON_NODE_OBJECT, "Set requires a JsonObjectNode"); + if(rc != PH7_OK) return rc; + SXUNUSED(nArg); + pThis = ph7_context_this(pCtx); + zName = ph7_value_to_string(apArg[0], &nName); + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + if(apArg[1] == 0 || !ph7_value_is_object(apArg[1]) || apArg[1]->x.pOther == 0) { + return JsonThrow(pCtx, JSON_ERROR_TYPE_MISMATCH, "JsonNode expected", 0, 0, + JsonFieldStr(pThis, "path", 0)); + } + rc = JsonCheckCycle(pCtx, apArg[1], pThis, 1); + if(rc != PH7_OK) return rc; + rc = JsonCheckDepth(pCtx, apArg[1], (int)JsonFieldInt(pThis, "depth") + 1); + if(rc != PH7_OK) return rc; + pChildren = JsonFieldContainer(pThis, "children"); + if(pChildren == 0) return PH7_CORRUPT; + { + ph7_value *pKey = ph7_context_new_scalar(pCtx); + if(pKey == 0) return PH7_ABORT; + (void)ph7_value_string(pKey, zName ? zName : "", nName); + (void)ph7_array_add_elem(pChildren, pKey, apArg[1]); + ph7_context_release_value(pCtx, pKey); + } + pThis = ph7_context_this(pCtx); /* reacquire after the insert */ + return JsonRepathChild(pCtx, pThis, apArg[1], zName, nName, 0, 0); +} +static int JsonNodeSetIndex(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis; + ph7_value *pChildren; + ph7_int64 iIndex; + int rc; + rc = JsonNodeCheckKind(pCtx, JSON_NODE_ARRAY, "SetIndex requires a JsonArrayNode"); + if(rc != PH7_OK) return rc; + SXUNUSED(nArg); + pThis = ph7_context_this(pCtx); + iIndex = ph7_value_to_int64(apArg[0]); + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + if(apArg[1] == 0 || !ph7_value_is_object(apArg[1]) || apArg[1]->x.pOther == 0) { + return JsonThrow(pCtx, JSON_ERROR_TYPE_MISMATCH, "JsonNode expected", 0, 0, + JsonFieldStr(pThis, "path", 0)); + } + pChildren = JsonFieldContainer(pThis, "children"); + { + ph7_value *pExisting = JsonArrayGet(pCtx, pChildren, iIndex); + if(pExisting) ph7_context_release_value(pCtx, pExisting); + if(pChildren == 0 || iIndex < 0 || pExisting == 0) { + return JsonThrow(pCtx, JSON_ERROR_INDEX_OUT_OF_RANGE, + "Index out of range", 0, 0, JsonFieldStr(pThis, "path", 0)); + } + } + rc = JsonCheckCycle(pCtx, apArg[1], pThis, 1); + if(rc != PH7_OK) return rc; + rc = JsonCheckDepth(pCtx, apArg[1], (int)JsonFieldInt(pThis, "depth") + 1); + if(rc != PH7_OK) return rc; + /* Cycle/depth checks may reserve arena slots and move live values. */ + pChildren = JsonFieldContainer(ph7_context_this(pCtx), "children"); + if(pChildren == 0) return PH7_CORRUPT; + (void)ph7_array_add_intkey_elem(pChildren, (int)iIndex, apArg[1]); + pThis = ph7_context_this(pCtx); /* reacquire after the insert */ + return JsonRepathChild(pCtx, pThis, apArg[1], 0, 0, (int)iIndex, 1); +} +struct JsonRemoveWalk { + ph7_context *pCtx; + ph7_value *pOut; + const char *zName; + int nName; + ph7_int64 iIndex; + int bByIndex; + int bRemoved; + int nNext; /* Next contiguous array key after removal */ +}; +static int JsonRemoveWalker(ph7_value *pKey, ph7_value *pValue, void *pUserData) { + struct JsonRemoveWalk *pWalk = (struct JsonRemoveWalk *)pUserData; + int bSkip = 0; + ph7_value sTmp; + if(pWalk->bByIndex) { + bSkip = pKey && ph7_value_is_int(pKey) && ph7_value_to_int64(pKey) == pWalk->iIndex; + } else if(pKey) { + int nKeyLen = 0; + const char *zKey = ph7_value_to_string(pKey, &nKeyLen); + bSkip = zKey && nKeyLen == pWalk->nName && + memcmp(zKey, pWalk->zName, (size_t)nKeyLen) == 0; + } + if(bSkip) { + pWalk->bRemoved = 1; + return 0; + } + PH7_MemObjInit(pWalk->pCtx->pVm, &sTmp); + (void)PH7_MemObjStore(pValue, &sTmp); + if(pWalk->bByIndex) { + /* Repack the surviving entries as 0..n-1; keeping the old keys would + * leave a hole that breaks GetIndex()/SetIndex() and auto-indexing. */ + (void)ph7_array_add_intkey_elem(pWalk->pOut, pWalk->nNext++, &sTmp); + } else { + /* Keep the original key object so embedded NUL bytes survive. */ + (void)ph7_array_add_elem(pWalk->pOut, pKey, &sTmp); + } + PH7_MemObjRelease(&sTmp); + return 0; +} +static int JsonNodeRemove(ph7_context *pCtx, int nArg, ph7_value **apArg, int bByIndex) { + ph7_value *pThis; + ph7_value *pChildren, *pNew; + struct JsonRemoveWalk sWalk; + const char *zName = ""; + int nName = 0, rc; + rc = JsonNodeCheckKind(pCtx, bByIndex ? JSON_NODE_ARRAY : JSON_NODE_OBJECT, + bByIndex ? "RemoveAt requires a JsonArrayNode" : "Remove requires a JsonObjectNode"); + if(rc != PH7_OK) return rc; + SXUNUSED(nArg); + pThis = ph7_context_this(pCtx); + pChildren = JsonFieldContainer(pThis, "children"); + pNew = ph7_context_new_array(pCtx); + if(pChildren == 0 || pNew == 0) { + if(pNew) ph7_context_release_value(pCtx, pNew); + return PH7_ABORT; + } + SyZero(&sWalk, sizeof(sWalk)); + sWalk.pCtx = pCtx; + sWalk.pOut = pNew; + sWalk.bByIndex = bByIndex; + if(bByIndex) { + sWalk.iIndex = ph7_value_to_int64(apArg[0]); + } else { + zName = ph7_value_to_string(apArg[0], &nName); + sWalk.zName = zName; + sWalk.nName = nName; + } + if(ph7_context_status(pCtx) != PH7_OK) { + ph7_context_release_value(pCtx, pNew); + return ph7_context_status(pCtx); + } + (void)ph7_array_walk(pChildren, JsonRemoveWalker, &sWalk); + (void)JsonFieldSetObj(pThis, "children", pNew); + ph7_context_release_value(pCtx, pNew); + /* Removal changes the subtree of every survivor: full repath. */ + rc = JsonRepathNode(pCtx, pThis); + if(rc != PH7_OK) return rc; + return ph7_result_bool(pCtx, sWalk.bRemoved); +} +static int JsonNodeRemoveName(ph7_context *pCtx, int nArg, ph7_value **apArg) { + return JsonNodeRemove(pCtx, nArg, apArg, 0); +} +static int JsonNodeRemoveAt(ph7_context *pCtx, int nArg, ph7_value **apArg) { + return JsonNodeRemove(pCtx, nArg, apArg, 1); +} +static int JsonNodeClear(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + ph7_value *pNew = ph7_context_new_array(pCtx); + SXUNUSED(nArg); SXUNUSED(apArg); + if(pNew == 0) return PH7_ABORT; + (void)JsonFieldSetObj(pThis, "children", pNew); + ph7_context_release_value(pCtx, pNew); + return PH7_OK; +} +static int JsonNodeToJson(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pOptions = nArg > 0 ? apArg[0] : 0; + return JsonSerialize(pCtx, ph7_context_this(pCtx), pOptions); +} +static int JsonNodeToString(ph7_context *pCtx, int nArg, ph7_value **apArg) { + json_opt sOpt; + json_ser sSer; + SXUNUSED(nArg); SXUNUSED(apArg); + JsonOptDefaults(&sOpt); + SyZero(&sSer, sizeof(sSer)); + sSer.pCtx = pCtx; + sSer.pOpt = &sOpt; + JsonSerNode(&sSer, ph7_context_this(pCtx)); + if(sSer.nOom) return PH7_ABORT; + if(sSer.nErr) { + return JsonThrow(pCtx, sSer.nErr, JsonErrorDescription(sSer.nErr), + sSer.nLine, sSer.nCol, sSer.zPath); + } + return PH7_OK; +} + +/* ------------------------------------------------------------------ */ +/* Method callbacks: JsonDocument / Json */ +/* ------------------------------------------------------------------ */ +static int JsonDocumentConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pRoot; + SXUNUSED(nArg); SXUNUSED(apArg); + pRoot = JsonNewNode(pCtx, JCLS_NULL, JSON_NODE_NULL_NODE, "$"); + if(pRoot == 0) return PH7_ABORT; + (void)JsonFieldSetObj(ph7_context_this(pCtx), "root", pRoot); + ph7_context_release_value(pCtx, pRoot); + return PH7_OK; +} +static int JsonDocumentParse(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pThis = ph7_context_this(pCtx); + ph7_value *pRoot = 0, *pOptions; + const char *zText; + int nByte = 0, rc; + if(nArg < 1 || !ph7_value_is_string(apArg[0])) { + return JsonThrow(pCtx, JSON_ERROR_SYNTAX, "Syntax error", 0, 0, "$"); + } + zText = ph7_value_to_string(apArg[0], &nByte); + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + pOptions = nArg > 1 ? apArg[1] : 0; + rc = JsonParseText(pCtx, zText, nByte, pOptions, &pRoot); + if(rc != PH7_OK) return rc; + (void)JsonFieldSetObj(pThis, "root", pRoot); + ph7_context_release_value(pCtx, pRoot); + return PH7_OK; +} +static int JsonDocumentGetRoot(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pRoot = JsonField(ph7_context_this(pCtx), "root"); + SXUNUSED(nArg); SXUNUSED(apArg); + return pRoot ? ph7_result_value(pCtx, pRoot) : ph7_result_null(pCtx); +} +static int JsonDocumentSetRoot(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pRoot = (nArg > 0 && ph7_value_is_object(apArg[0]) && apArg[0]->x.pOther != 0) + ? apArg[0] : 0; + int rc; + if(pRoot == 0) { + return JsonThrow(pCtx, JSON_ERROR_TYPE_MISMATCH, "JsonNode expected", 0, 0, "$"); + } + /* A subtree that already contains itself cannot become a document root. */ + rc = JsonCheckCycle(pCtx, pRoot, pRoot, 0); + if(rc != PH7_OK) return rc; + rc = JsonCheckDepth(pCtx, pRoot, 0); + if(rc != PH7_OK) return rc; + rc = JsonFieldSetObj(ph7_context_this(pCtx), "root", pRoot); + if(rc != PH7_OK) return rc; + return JsonRepathFrom(pCtx, pRoot, "$", 0); +} +static int JsonDocumentToJson(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pRoot = JsonField(ph7_context_this(pCtx), "root"); + return JsonSerialize(pCtx, pRoot, nArg > 0 ? apArg[0] : 0); +} +static int JsonParse(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_vm *pVm = pCtx->pVm; + ph7_class *pClass = PH7_VmExtractClass(pVm, JCLS_DOC, sizeof(JCLS_DOC) - 1, FALSE); + ph7_class_instance *pInst; + ph7_value *pDoc, *pRoot = 0, *pOptions; + const char *zText; + int nByte = 0, rc; + if(pClass == 0) return PH7_ABORT; + if(nArg < 1 || !ph7_value_is_string(apArg[0])) { + return JsonThrow(pCtx, JSON_ERROR_SYNTAX, "Syntax error", 0, 0, "$"); + } + zText = ph7_value_to_string(apArg[0], &nByte); + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + pOptions = nArg > 1 ? apArg[1] : 0; + rc = JsonParseText(pCtx, zText, nByte, pOptions, &pRoot); + if(rc != PH7_OK) return rc; + pDoc = ph7_context_new_scalar(pCtx); + if(pDoc == 0) { + ph7_context_release_value(pCtx, pRoot); + return PH7_ABORT; + } + pInst = PH7_NewClassInstance(pVm, pClass); + if(pInst == 0) { + ph7_context_release_value(pCtx, pDoc); + ph7_context_release_value(pCtx, pRoot); + PH7_VmMemoryError(pVm); + return PH7_ABORT; + } + if(pInst->iRef < 1) pInst->iRef = 1; + PH7_MemObjRelease(pDoc); + pDoc->x.pOther = pInst; + MemObjSetType(pDoc, MEMOBJ_OBJ); + (void)JsonFieldSetObj(pDoc, "root", pRoot); + ph7_context_release_value(pCtx, pRoot); + return ph7_result_value(pCtx, pDoc); +} +static int JsonParseNode(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pRoot = 0, *pOptions; + const char *zText; + int nByte = 0, rc; + if(nArg < 1 || !ph7_value_is_string(apArg[0])) { + return JsonThrow(pCtx, JSON_ERROR_SYNTAX, "Syntax error", 0, 0, "$"); + } + zText = ph7_value_to_string(apArg[0], &nByte); + if(ph7_context_status(pCtx) != PH7_OK) return ph7_context_status(pCtx); + pOptions = nArg > 1 ? apArg[1] : 0; + rc = JsonParseText(pCtx, zText, nByte, pOptions, &pRoot); + if(rc != PH7_OK) return rc; + rc = ph7_result_value(pCtx, pRoot); + ph7_context_release_value(pCtx, pRoot); + return rc; +} +static int JsonSerializeFn(ph7_context *pCtx, int nArg, ph7_value **apArg) { + return JsonSerialize(pCtx, nArg > 0 ? apArg[0] : 0, nArg > 1 ? apArg[1] : 0); +} + +/* ------------------------------------------------------------------ */ +/* Native class registration */ +/* ------------------------------------------------------------------ */ +static ph7_constant_def aNodeTypeConst[] = { + { "OBJECT", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ARRAY", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "STRING", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "NUMBER", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "BOOLEAN", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "NULL_NODE", 0, PH7_MEMBER_PUBLIC, 0, 0 }, +}; +static const int aNodeTypeValue[] = { + JSON_NODE_OBJECT, JSON_NODE_ARRAY, JSON_NODE_STRING, + JSON_NODE_NUMBER, JSON_NODE_BOOLEAN, JSON_NODE_NULL_NODE +}; +static ph7_constant_def aExceptionConst[] = { + { "ERROR_NONE", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_DEPTH", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_STATE_MISMATCH", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_CTRL_CHAR", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_SYNTAX", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_UTF8", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_TYPE_MISMATCH", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_KEY_NOT_FOUND", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_INDEX_OUT_OF_RANGE", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_DUPLICATE_KEY", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_INVALID_OPERATION", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_INVALID_OPTION", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_READONLY_OPTION", 0, PH7_MEMBER_PUBLIC, 0, 0 }, +}; +static const int aExceptionValue[] = { + JSON_ERROR_NONE, JSON_ERROR_DEPTH, JSON_ERROR_STATE_MISMATCH, JSON_ERROR_CTRL_CHAR, + JSON_ERROR_SYNTAX, JSON_ERROR_UTF8, JSON_ERROR_TYPE_MISMATCH, JSON_ERROR_KEY_NOT_FOUND, + JSON_ERROR_INDEX_OUT_OF_RANGE, JSON_ERROR_DUPLICATE_KEY, JSON_ERROR_INVALID_OPERATION, + JSON_ERROR_INVALID_OPTION, JSON_ERROR_READONLY_OPTION +}; +static ph7_constant_def aOptionsConst[] = { + { "KEEP_LAST", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "KEEP_FIRST", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "REJECT", 0, PH7_MEMBER_PUBLIC, 0, 0 }, +}; +static const int aOptionsValue[] = { JSON_DUP_KEEP_LAST, JSON_DUP_KEEP_FIRST, JSON_DUP_REJECT }; + +static sxi32 JsonRegisterClasses(ph7_vm *pVm) { + static ph7_param_def aExcCtor[] = { + JP("message", STRING), JP("code", INT), JPN("inputLine", JTY(INT)), + JPN("inputColumn", JTY(INT)), JPN("path", JTY(STRING)) + }; + static const ph7_param_def aExcDesc[] = { JP("code", INT) }; + static const ph7_param_def aNodeName[] = { JP("name", STRING) }; + static const ph7_param_def aNodeIndex[] = { JP("index", INT) }; + static const ph7_param_def aNodeSet[] = { + JP("name", STRING), JPN("node", JNM("JsonNode")) + }; + static const ph7_param_def aNodeSetIndex[] = { + JP("index", INT), JPN("node", JNM("JsonNode")) + }; + static const ph7_param_def aNodeAdd[] = { JPN("node", JNM("JsonNode")) }; + static const ph7_param_def aNodeCtorStr[] = { JP("value", STRING) }; + static const ph7_param_def aNodeCtorInt[] = { JP("value", INT) }; + static const ph7_param_def aNodeCtorFloat[] = { JP("value", FLOAT) }; + static const ph7_param_def aNodeCtorRaw[] = { JP("rawNumber", STRING) }; + static const ph7_param_def aNodeCtorBool[] = { JP("value", BOOL) }; + static ph7_param_def aToJson[] = { JPO("options", JNM("JsonOptions"), 0) }; + static const ph7_param_def aSetBool[] = { JP("value", BOOL) }; + static const ph7_param_def aSetInt[] = { JP("value", INT) }; + static const ph7_param_def aSetStr[] = { JP("value", STRING) }; + static ph7_param_def aParse[] = { + JP("text", STRING), JPO("options", JNM("JsonOptions"), 0) + }; + static ph7_param_def aDocParse[] = { + JP("text", STRING), JPO("options", JNM("JsonOptions"), 0) + }; + static ph7_param_def aDocToJson[] = { JPO("options", JNM("JsonOptions"), 0) }; + static ph7_param_def aSerialize[] = { + JPN("node", JNM("JsonNode")), JPO("options", JNM("JsonOptions"), 0) + }; + static const ph7_method_def aExcMethod[] = { + { "__construct", JTY(VOID), aExcCtor, 5, JsonExceptionConstruct, 0, 0 }, + { "GetInputLine", JTY(INT), 0, 0, JsonExceptionField, (void *)"inputLine", PH7_MEMBER_PUBLIC }, + { "GetInputColumn", JTY(INT), 0, 0, JsonExceptionField, (void *)"inputColumn", PH7_MEMBER_PUBLIC }, + { "GetPath", JTY(STRING), 0, 0, JsonExceptionField, (void *)"path", PH7_MEMBER_PUBLIC }, + { "GetDescription", JTY(STRING), aExcDesc, 1, JsonExceptionDescription, 0, + PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC } + }; + static const ph7_field_def aExcField[] = { + { "inputLine", JTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "inputColumn", JTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "path", JTY(STRING), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + }; + static const char *const aExcBase[] = { "Exception" }; + static const ph7_method_def aNodeMethod[] = { + { "GetNodeType", JTY(INT), 0, 0, JsonNodeGetIntField, (void *)"kind", PH7_MEMBER_PUBLIC }, + { "GetPath", JTY(STRING), 0, 0, JsonNodeGetStrField, (void *)"path", PH7_MEMBER_PUBLIC }, + { "GetDepth", JTY(INT), 0, 0, JsonNodeGetDepth, 0, PH7_MEMBER_PUBLIC }, + { "GetProperty", JNM("JsonNode"), aNodeName, 1, JsonNodeGetProperty, 0, PH7_MEMBER_PUBLIC }, + { "HasProperty", JTY(BOOL), aNodeName, 1, JsonNodeHasProperty, 0, PH7_MEMBER_PUBLIC }, + { "GetPropertyNames", JTYARR(STRING), 0, 0, JsonNodeGetPropertyNames, 0, PH7_MEMBER_PUBLIC }, + { "GetIndex", JNM("JsonNode"), aNodeIndex, 1, JsonNodeGetIndex, 0, PH7_MEMBER_PUBLIC }, + { "GetCount", JTY(INT), 0, 0, JsonNodeGetCount, 0, PH7_MEMBER_PUBLIC }, + { "GetChildren", JAR("JsonNode"), 0, 0, JsonNodeGetChildren, 0, PH7_MEMBER_PUBLIC }, + { "Add", JTY(VOID), aNodeAdd, 1, JsonNodeAdd, 0, PH7_MEMBER_PUBLIC }, + { "Set", JTY(VOID), aNodeSet, 2, JsonNodeSet, 0, PH7_MEMBER_PUBLIC }, + { "SetIndex", JTY(VOID), aNodeSetIndex, 2, JsonNodeSetIndex, 0, PH7_MEMBER_PUBLIC }, + { "Remove", JTY(BOOL), aNodeName, 1, JsonNodeRemoveName, 0, PH7_MEMBER_PUBLIC }, + { "RemoveAt", JTY(BOOL), aNodeIndex, 1, JsonNodeRemoveAt, 0, PH7_MEMBER_PUBLIC }, + { "Clear", JTY(VOID), 0, 0, JsonNodeClear, 0, PH7_MEMBER_PUBLIC }, + { "GetString", JTY(STRING), 0, 0, JsonNodeGetString, 0, PH7_MEMBER_PUBLIC }, + { "GetInt", JTY(INT), 0, 0, JsonNodeGetInt, 0, PH7_MEMBER_PUBLIC }, + { "GetDouble", JTY(FLOAT), 0, 0, JsonNodeGetDouble, 0, PH7_MEMBER_PUBLIC }, + { "GetBool", JTY(BOOL), 0, 0, JsonNodeGetBool, 0, PH7_MEMBER_PUBLIC }, + { "GetRawNumber", JTY(STRING), 0, 0, JsonNodeGetRawNumber, 0, PH7_MEMBER_PUBLIC }, + { "IsNull", JTY(BOOL), 0, 0, JsonNodeIsNull, 0, PH7_MEMBER_PUBLIC }, + { "ToJson", JTY(STRING), aToJson, 1, JsonNodeToJson, 0, PH7_MEMBER_PUBLIC }, + { "__toString", JTY(STRING), 0, 0, JsonNodeToString, 0, 0 }, + }; + static ph7_field_def aNodeField[] = { + { "kind", JTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "path", JTY(STRING), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "text", JTY(STRING), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "intValue", JTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "realValue", JTY(FLOAT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "boolValue", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "rawNumber", JTY(STRING), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "children", JAR("JsonNode"), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "depth", JTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + }; +#define JSON_DEPTH_FIELD_INDEX 8 + static const char *const aNodeBase[] = { "JsonNode" }; + static const ph7_method_def aObjMethod[] = { + { "__construct", JTY(VOID), 0, 0, JsonNodeConstruct, (void *)(long)JSON_NODE_OBJECT, 0 } + }; + static const ph7_method_def aArrMethod[] = { + { "__construct", JTY(VOID), 0, 0, JsonNodeConstruct, (void *)(long)JSON_NODE_ARRAY, 0 } + }; + static const ph7_method_def aStrMethod[] = { + { "__construct", JTY(VOID), aNodeCtorStr, 1, JsonNodeCtorString, (void *)(long)JSON_NODE_STRING, 0 } + }; + static const ph7_method_def aNumMethod[] = { + { "__construct", JTY(VOID), aNodeCtorInt, 1, JsonNodeCtorInt, (void *)(long)JSON_NODE_NUMBER, 0 }, + { "__construct", JTY(VOID), aNodeCtorFloat, 1, JsonNodeCtorFloat, (void *)(long)JSON_NODE_NUMBER, 0 }, + { "__construct", JTY(VOID), aNodeCtorRaw, 1, JsonNodeCtorRaw, (void *)(long)JSON_NODE_NUMBER, 0 }, + }; + static const ph7_method_def aBoolMethod[] = { + { "__construct", JTY(VOID), aNodeCtorBool, 1, JsonNodeCtorBool, (void *)(long)JSON_NODE_BOOLEAN, 0 } + }; + static const ph7_method_def aNullMethod[] = { + { "__construct", JTY(VOID), 0, 0, JsonNodeConstruct, (void *)(long)JSON_NODE_NULL_NODE, 0 } + }; + static ph7_field_def aOptField[] = { + { "prettyPrint", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "unescapedUnicode", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "unescapedSlashes", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "hexTag", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "hexAmp", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "hexApos", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "hexQuot", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "numericCheck", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "bigintAsString", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "allowComments", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "allowTrailingComma", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "duplicateKeyPolicy", JTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "maxDepth", JTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "indent", JTY(STRING), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "readOnly", JTY(BOOL), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + }; + static const ph7_method_def aOptMethod[] = { + { "__construct", JTY(VOID), 0, 0, JsonOptionsConstruct, 0, 0 }, + { "MakeReadOnly", JTY(VOID), 0, 0, JsonOptionsMakeReadOnly, 0, PH7_MEMBER_PUBLIC }, + { "IsReadOnly", JTY(BOOL), 0, 0, JsonOptionsIsReadOnly, 0, PH7_MEMBER_PUBLIC }, + { "Validate", JTY(VOID), 0, 0, JsonOptionsValidate, 0, PH7_MEMBER_PUBLIC }, + { "Copy", JNM("JsonOptions"), 0, 0, JsonOptionsCopy, 0, PH7_MEMBER_PUBLIC }, + { "GetPrettyPrint", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"prettyPrint", PH7_MEMBER_PUBLIC }, + { "SetPrettyPrint", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"prettyPrint", PH7_MEMBER_PUBLIC }, + { "GetUnescapedUnicode", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"unescapedUnicode", PH7_MEMBER_PUBLIC }, + { "SetUnescapedUnicode", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"unescapedUnicode", PH7_MEMBER_PUBLIC }, + { "GetUnescapedSlashes", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"unescapedSlashes", PH7_MEMBER_PUBLIC }, + { "SetUnescapedSlashes", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"unescapedSlashes", PH7_MEMBER_PUBLIC }, + { "GetHexTag", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"hexTag", PH7_MEMBER_PUBLIC }, + { "SetHexTag", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"hexTag", PH7_MEMBER_PUBLIC }, + { "GetHexAmp", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"hexAmp", PH7_MEMBER_PUBLIC }, + { "SetHexAmp", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"hexAmp", PH7_MEMBER_PUBLIC }, + { "GetHexApos", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"hexApos", PH7_MEMBER_PUBLIC }, + { "SetHexApos", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"hexApos", PH7_MEMBER_PUBLIC }, + { "GetHexQuot", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"hexQuot", PH7_MEMBER_PUBLIC }, + { "SetHexQuot", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"hexQuot", PH7_MEMBER_PUBLIC }, + { "GetNumericCheck", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"numericCheck", PH7_MEMBER_PUBLIC }, + { "SetNumericCheck", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"numericCheck", PH7_MEMBER_PUBLIC }, + { "GetBigintAsString", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"bigintAsString", PH7_MEMBER_PUBLIC }, + { "SetBigintAsString", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"bigintAsString", PH7_MEMBER_PUBLIC }, + { "GetAllowComments", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"allowComments", PH7_MEMBER_PUBLIC }, + { "SetAllowComments", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"allowComments", PH7_MEMBER_PUBLIC }, + { "GetAllowTrailingComma", JTY(BOOL), 0, 0, JsonOptionsGet, (void *)"allowTrailingComma", PH7_MEMBER_PUBLIC }, + { "SetAllowTrailingComma", JTY(VOID), aSetBool, 1, JsonOptionsSetBool, (void *)"allowTrailingComma", PH7_MEMBER_PUBLIC }, + { "GetDuplicateKeyPolicy", JTY(INT), 0, 0, JsonOptionsGet, (void *)"duplicateKeyPolicy", PH7_MEMBER_PUBLIC }, + { "SetDuplicateKeyPolicy", JTY(VOID), aSetInt, 1, JsonOptionsSetInt, (void *)"duplicateKeyPolicy", PH7_MEMBER_PUBLIC }, + { "GetMaxDepth", JTY(INT), 0, 0, JsonOptionsGet, (void *)"maxDepth", PH7_MEMBER_PUBLIC }, + { "SetMaxDepth", JTY(VOID), aSetInt, 1, JsonOptionsSetInt, (void *)"maxDepth", PH7_MEMBER_PUBLIC }, + { "GetIndent", JTY(STRING), 0, 0, JsonOptionsGet, (void *)"indent", PH7_MEMBER_PUBLIC }, + { "SetIndent", JTY(VOID), aSetStr, 1, JsonOptionsSetIndent, 0, PH7_MEMBER_PUBLIC }, + }; + static const ph7_method_def aDocMethod[] = { + { "__construct", JTY(VOID), 0, 0, JsonDocumentConstruct, 0, 0 }, + { "Parse", JTY(VOID), aDocParse, 2, JsonDocumentParse, 0, PH7_MEMBER_PUBLIC }, + { "GetRoot", JNM("JsonNode"), 0, 0, JsonDocumentGetRoot, 0, PH7_MEMBER_PUBLIC }, + { "SetRoot", JTY(VOID), aSerialize, 1, JsonDocumentSetRoot, 0, PH7_MEMBER_PUBLIC }, + { "ToJson", JTY(STRING), aDocToJson, 1, JsonDocumentToJson, 0, PH7_MEMBER_PUBLIC }, + }; + static const ph7_field_def aDocField[] = { + { "root", JNM("JsonNode"), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + }; + static const ph7_method_def aFacadeMethod[] = { + { "Parse", JNM("JsonDocument"), aParse, 2, JsonParse, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC }, + { "ParseNode", JNM("JsonNode"), aParse, 2, JsonParseNode, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC }, + { "Serialize", JTY(STRING), aSerialize, 2, JsonSerializeFn, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC }, + }; + ph7_class_def sExc = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_EXC, + aExcField, SX_ARRAYSIZE(aExcField), aExceptionConst, SX_ARRAYSIZE(aExceptionConst), + aExcMethod, SX_ARRAYSIZE(aExcMethod), 0, aExcBase, 1, 0, 0, 0, 0 }; + ph7_class_def sNode = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_NODE, + aNodeField, SX_ARRAYSIZE(aNodeField), 0, 0, aNodeMethod, SX_ARRAYSIZE(aNodeMethod), + 0, 0, 0, 0, 0, 0, 0 }; + ph7_class_def sObject = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_OBJECT, + 0, 0, 0, 0, aObjMethod, SX_ARRAYSIZE(aObjMethod), 0, aNodeBase, 1, 0, 0, 0, 0 }; + ph7_class_def sArray = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_ARRAY, + 0, 0, 0, 0, aArrMethod, SX_ARRAYSIZE(aArrMethod), 0, aNodeBase, 1, 0, 0, 0, 0 }; + ph7_class_def sString = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_STRING, + 0, 0, 0, 0, aStrMethod, SX_ARRAYSIZE(aStrMethod), 0, aNodeBase, 1, 0, 0, 0, 0 }; + ph7_class_def sNumber = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_NUMBER, + 0, 0, 0, 0, aNumMethod, SX_ARRAYSIZE(aNumMethod), 0, aNodeBase, 1, 0, 0, 0, 0 }; + ph7_class_def sBool = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_BOOL, + 0, 0, 0, 0, aBoolMethod, SX_ARRAYSIZE(aBoolMethod), 0, aNodeBase, 1, 0, 0, 0, 0 }; + ph7_class_def sNull = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_NULL, + 0, 0, 0, 0, aNullMethod, SX_ARRAYSIZE(aNullMethod), 0, aNodeBase, 1, 0, 0, 0, 0 }; + ph7_class_def sOpt = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_OPTIONS, + aOptField, SX_ARRAYSIZE(aOptField), aOptionsConst, SX_ARRAYSIZE(aOptionsConst), + aOptMethod, SX_ARRAYSIZE(aOptMethod), 0, 0, 0, 0, 0, 0, 0 }; + ph7_class_def sDoc = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_DOC, + aDocField, SX_ARRAYSIZE(aDocField), 0, 0, aDocMethod, SX_ARRAYSIZE(aDocMethod), + 0, 0, 0, 0, 0, 0, 0 }; + ph7_class_def sFacade = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_FACADE, + 0, 0, 0, 0, aFacadeMethod, SX_ARRAYSIZE(aFacadeMethod), 0, 0, 0, 0, 0, 0, 0 }; + ph7_class_def sKind = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, JCLS_KIND, + 0, 0, aNodeTypeConst, SX_ARRAYSIZE(aNodeTypeConst), 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + ph7_value *apExc[SX_ARRAYSIZE(aExceptionConst)]; + ph7_value *apKind[SX_ARRAYSIZE(aNodeTypeConst)]; + ph7_value *apOptConst[SX_ARRAYSIZE(aOptionsConst)]; + ph7_value *apInit[SX_ARRAYSIZE(aOptField)]; + ph7_value *apCtorDef[3]; + ph7_value *pDepthInit = 0; + ph7_value *pDefaultOpts = 0; + ph7_class *pOptClass; + ph7_class_instance *pInst; sxu32 n; + sxi32 rc = PH7_OK; + SyZero(apExc, sizeof(apExc)); + SyZero(apKind, sizeof(apKind)); + SyZero(apOptConst, sizeof(apOptConst)); + SyZero(apInit, sizeof(apInit)); + SyZero(apCtorDef, sizeof(apCtorDef)); + /* Allocate constant and default snapshots. */ + for(n = 0 ; n < SX_ARRAYSIZE(apExc) ; ++n) { + apExc[n] = ph7_new_scalar(pVm); + if(apExc[n] == 0) { rc = PH7_NOMEM; goto Cleanup; } + ph7_value_int(apExc[n], aExceptionValue[n]); + aExceptionConst[n].pValue = apExc[n]; + } + for(n = 0 ; n < SX_ARRAYSIZE(apKind) ; ++n) { + apKind[n] = ph7_new_scalar(pVm); + if(apKind[n] == 0) { rc = PH7_NOMEM; goto Cleanup; } + ph7_value_int(apKind[n], aNodeTypeValue[n]); + aNodeTypeConst[n].pValue = apKind[n]; + } + for(n = 0 ; n < SX_ARRAYSIZE(apOptConst) ; ++n) { + apOptConst[n] = ph7_new_scalar(pVm); + if(apOptConst[n] == 0) { rc = PH7_NOMEM; goto Cleanup; } + ph7_value_int(apOptConst[n], aOptionsValue[n]); + aOptionsConst[n].pValue = apOptConst[n]; + } + for(n = 0 ; n < SX_ARRAYSIZE(apInit) ; ++n) { + apInit[n] = ph7_new_scalar(pVm); + if(apInit[n] == 0) { rc = PH7_NOMEM; goto Cleanup; } + if(n < 11) { + ph7_value_bool(apInit[n], 0); + } else if(n == 11) { + ph7_value_int(apInit[n], JSON_DUP_KEEP_LAST); + } else if(n == 12) { + ph7_value_int(apInit[n], JSON_DEFAULT_MAX_DEPTH); + } else if(n == 13) { + ph7_value_string(apInit[n], " ", 2); + } else { + ph7_value_bool(apInit[n], 0); /* readOnly */ + } + aOptField[n].pInitial = apInit[n]; + } + pDepthInit = ph7_new_scalar(pVm); + if(pDepthInit == 0) { rc = PH7_NOMEM; goto Cleanup; } + ph7_value_int(pDepthInit, 0); + aNodeField[JSON_DEPTH_FIELD_INDEX].pInitial = pDepthInit; + for(n = 0 ; n < SX_ARRAYSIZE(apCtorDef) ; ++n) { + apCtorDef[n] = ph7_new_scalar(pVm); + if(apCtorDef[n] == 0) { rc = PH7_NOMEM; goto Cleanup; } + } + ph7_value_int(apCtorDef[0], 0); + ph7_value_int(apCtorDef[1], 0); + ph7_value_string(apCtorDef[2], "", 0); + aExcCtor[2].pDefault = apCtorDef[0]; + aExcCtor[3].pDefault = apCtorDef[1]; + aExcCtor[4].pDefault = apCtorDef[2]; + /* JsonOptions must exist before the default parameter snapshot can be + * built, so it is registered first (see report). */ + rc = ph7_create_class(pVm, &sOpt); + if(rc != PH7_OK) goto Cleanup; + pOptClass = PH7_VmExtractClass(pVm, JCLS_OPTIONS, sizeof(JCLS_OPTIONS) - 1, FALSE); + if(pOptClass == 0) { rc = PH7_ABORT; goto Cleanup; } + pInst = PH7_NewClassInstance(pVm, pOptClass); + if(pInst == 0) { rc = PH7_NOMEM; goto Cleanup; } + if(pInst->iRef < 1) pInst->iRef = 1; + pDefaultOpts = ph7_new_scalar(pVm); + if(pDefaultOpts == 0) { + PH7_ClassInstanceUnref(pInst); + rc = PH7_NOMEM; + goto Cleanup; + } + PH7_MemObjRelease(pDefaultOpts); + pDefaultOpts->x.pOther = pInst; + MemObjSetType(pDefaultOpts, MEMOBJ_OBJ); + aToJson[0].pDefault = pDefaultOpts; + aDocParse[1].pDefault = pDefaultOpts; + aDocToJson[0].pDefault = pDefaultOpts; + aParse[1].pDefault = pDefaultOpts; + aSerialize[1].pDefault = pDefaultOpts; + rc = ph7_create_class(pVm, &sExc); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sNode); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sObject); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sArray); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sString); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sNumber); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sBool); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sNull); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sDoc); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sFacade); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sKind); +Cleanup: + aToJson[0].pDefault = 0; + aDocParse[1].pDefault = 0; + aDocToJson[0].pDefault = 0; + aParse[1].pDefault = 0; + aSerialize[1].pDefault = 0; + aExcCtor[2].pDefault = 0; + aExcCtor[3].pDefault = 0; + aExcCtor[4].pDefault = 0; + aNodeField[JSON_DEPTH_FIELD_INDEX].pInitial = 0; + if(pDepthInit) { + ph7_release_value(pVm, pDepthInit); + } + if(pDefaultOpts) { + ph7_release_value(pVm, pDefaultOpts); + } + for(n = 0 ; n < SX_ARRAYSIZE(apCtorDef) ; ++n) { + if(apCtorDef[n]) ph7_release_value(pVm, apCtorDef[n]); + } + for(n = 0 ; n < SX_ARRAYSIZE(apInit) ; ++n) { + if(apInit[n]) { + ph7_release_value(pVm, apInit[n]); + aOptField[n].pInitial = 0; + } + } + for(n = 0 ; n < SX_ARRAYSIZE(apOptConst) ; ++n) { + if(apOptConst[n]) { + ph7_release_value(pVm, apOptConst[n]); + aOptionsConst[n].pValue = 0; + } + } + for(n = 0 ; n < SX_ARRAYSIZE(apKind) ; ++n) { + if(apKind[n]) { + ph7_release_value(pVm, apKind[n]); + aNodeTypeConst[n].pValue = 0; + } + } + for(n = 0 ; n < SX_ARRAYSIZE(apExc) ; ++n) { + if(apExc[n]) { + ph7_release_value(pVm, apExc[n]); + aExceptionConst[n].pValue = 0; + } + } + return rc; +} + +PH7_PRIVATE sxi32 initializeModule(ph7_vm *pVm, ph7_real *ver, SyString *desc) { desc->zString = MODULE_DESC; *ver = MODULE_VER; - for(n = 0; n < SX_ARRAYSIZE(jsonConstList); ++n) { - rc = ph7_create_constant(&(*pVm), jsonConstList[n].zName, jsonConstList[n].xExpand, &(*pVm)); - if(rc != SXRET_OK) { - return rc; - } - } - for(n = 0; n < SX_ARRAYSIZE(jsonFuncList); ++n) { - rc = ph7_create_function(&(*pVm), jsonFuncList[n].zName, jsonFuncList[n].xFunc, &(*pVm)); - if(rc != SXRET_OK) { - return rc; - } - } - return SXRET_OK; + return JsonRegisterClasses(pVm); } diff --git a/modules/json/json.h b/modules/json/json.h index e494f48..f937091 100644 --- a/modules/json/json.h +++ b/modules/json/json.h @@ -1,8 +1,8 @@ /** * @PROJECT AerScript Interpreter * @COPYRIGHT See COPYING in the top level directory - * @FILE modules/json/json.c - * @DESCRIPTION JavaScript Object Notation (JSON) module for AerScript Interpreter + * @FILE modules/json/json.h + * @DESCRIPTION Typed JSON DOM module for AerScript Interpreter * @DEVELOPERS Symisc Systems * Rafal Kupiec */ @@ -15,19 +15,36 @@ #define MODULE_DESC "JSON Module" #define MODULE_VER 1.0 -/* The following constants can be combined to form options for json_encode(). */ -#define JSON_HEX_TAG 0x01 /* All < and > are converted to \u003C and \u003E. */ -#define JSON_HEX_AMP 0x02 /* All &s are converted to \u0026. */ -#define JSON_HEX_APOS 0x04 /* All ' are converted to \u0027. */ -#define JSON_HEX_QUOT 0x08 /* All " are converted to \u0022. */ -#define JSON_FORCE_OBJECT 0x10 /* Outputs an object rather than an array */ -#define JSON_NUMERIC_CHECK 0x20 /* Encodes numeric strings as numbers. */ -#define JSON_BIGINT_AS_STRING 0x40 /* Decode big integers as strings. */ -#define JSON_PRETTY_PRINT 0x80 /* Use whitespace in returned data to format it.*/ -#define JSON_UNESCAPED_SLASHES 0x100 /* Don't escape '/' */ -#define JSON_UNESCAPED_UNICODE 0x200 /* Not used */ +/* JsonNodeType constants. NULL is a language keyword, so the null node kind + * is published as NULL_NODE (the contract's documented fallback). */ +#define JSON_NODE_OBJECT 1 +#define JSON_NODE_ARRAY 2 +#define JSON_NODE_STRING 3 +#define JSON_NODE_NUMBER 4 +#define JSON_NODE_BOOLEAN 5 +#define JSON_NODE_NULL_NODE 6 -/* Possible tokens from the JSON tokenization process */ +/* JsonException error codes. */ +#define JSON_ERROR_NONE 0 +#define JSON_ERROR_DEPTH 1 +#define JSON_ERROR_STATE_MISMATCH 2 +#define JSON_ERROR_CTRL_CHAR 3 +#define JSON_ERROR_SYNTAX 4 +#define JSON_ERROR_UTF8 5 +#define JSON_ERROR_TYPE_MISMATCH 6 +#define JSON_ERROR_KEY_NOT_FOUND 7 +#define JSON_ERROR_INDEX_OUT_OF_RANGE 8 +#define JSON_ERROR_DUPLICATE_KEY 9 +#define JSON_ERROR_INVALID_OPERATION 10 +#define JSON_ERROR_INVALID_OPTION 11 +#define JSON_ERROR_READONLY_OPTION 12 + +/* JsonOptions duplicate-key policies. */ +#define JSON_DUP_KEEP_LAST 0 +#define JSON_DUP_KEEP_FIRST 1 +#define JSON_DUP_REJECT 2 + +/* Possible tokens from the JSON tokenization process. */ #define JSON_TK_TRUE 0x001 /* Boolean true */ #define JSON_TK_FALSE 0x002 /* Boolean false */ #define JSON_TK_STR 0x004 /* String enclosed in double quotes */ @@ -41,92 +58,6 @@ #define JSON_TK_COMMA 0x400 /* Single comma ',' */ #define JSON_TK_INVALID 0x800 /* Unexpected token */ -#define JSON_DECODE_ASSOC 0x01 /* Decode a JSON object as an associative array */ -#define JSON_DECODE_NUMERIC 0x02 /* Decode a JSON object as a numeric array */ - -/* - * JSON encoder state is stored in an instance - * of the following structure. - */ -typedef struct json_private_data json_private_data; -struct json_private_data { - ph7_context *pCtx; /* Call context */ - int isFirst; /* True if first encoded entry */ - int iFlags; /* JSON encoding flags */ - int nRecCount; /* Recursion count */ - sxi32 bObject; /* True if the current container is encoded as an object */ - sxi32 bAbort; /* True if the encoding process was aborted */ -}; - -/* - * JSON decoded input consumer callback signature. - */ -typedef int (*ProcJsonConsumer)(ph7_context *, ph7_value *, ph7_value *, void *); - -/* - * JSON decoder state is kept in the following structure. - */ -typedef struct json_decoder json_decoder; -struct json_decoder { - ph7_context *pCtx; /* Call context */ - ProcJsonConsumer xConsumer; /* Consumer callback */ - void *pUserData; /* Last argument to xConsumer() */ - int iFlags; /* Configuration flags */ - SyToken *pIn; /* Token stream */ - SyToken *pEnd; /* End of the token stream */ - int rec_depth; /* Recursion limit */ - int rec_count; /* Current nesting level */ - int *pErr; /* JSON decoding error if any */ -}; - -/* Forward reference */ -static int VmJsonArrayEncode(ph7_value *pKey, ph7_value *pValue, void *pUserData); -static int VmJsonObjectEncode(const char *zAttr, ph7_value *pValue, void *pUserData); -static int VmJsonArrayDecoder(ph7_context *pCtx, ph7_value *pKey, ph7_value *pWorker, void *pUserData); -static void PH7_JSON_HEX_TAG_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_HEX_AMP_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_HEX_APOS_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_HEX_QUOT_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_FORCE_OBJECT_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_NUMERIC_CHECK_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_BIGINT_AS_STRING_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_PRETTY_PRINT_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_UNESCAPED_SLASHES_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_UNESCAPED_UNICODE_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_ERROR_NONE_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_ERROR_DEPTH_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_ERROR_STATE_MISMATCH_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_ERROR_CTRL_CHAR_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_ERROR_SYNTAX_Const(ph7_value *pVal, void *pUserData); -static void PH7_JSON_ERROR_UTF8_Const(ph7_value *pVal, void *pUserData); -static int vm_builtin_json_encode(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_json_last_error(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_json_decode(ph7_context *pCtx, int nArg, ph7_value **apArg); PH7_PRIVATE sxi32 initializeModule(ph7_vm *pVm, ph7_real *ver, SyString *desc); -static const ph7_builtin_constant jsonConstList[] = { - {"JSON_HEX_TAG", PH7_JSON_HEX_TAG_Const}, - {"JSON_HEX_AMP", PH7_JSON_HEX_AMP_Const}, - {"JSON_HEX_APOS", PH7_JSON_HEX_APOS_Const}, - {"JSON_HEX_QUOT", PH7_JSON_HEX_QUOT_Const}, - {"JSON_FORCE_OBJECT", PH7_JSON_FORCE_OBJECT_Const}, - {"JSON_NUMERIC_CHECK", PH7_JSON_NUMERIC_CHECK_Const}, - {"JSON_BIGINT_AS_STRING", PH7_JSON_BIGINT_AS_STRING_Const}, - {"JSON_PRETTY_PRINT", PH7_JSON_PRETTY_PRINT_Const}, - {"JSON_UNESCAPED_SLASHES", PH7_JSON_UNESCAPED_SLASHES_Const}, - {"JSON_UNESCAPED_UNICODE", PH7_JSON_UNESCAPED_UNICODE_Const}, - {"JSON_ERROR_NONE", PH7_JSON_ERROR_NONE_Const}, - {"JSON_ERROR_DEPTH", PH7_JSON_ERROR_DEPTH_Const}, - {"JSON_ERROR_STATE_MISMATCH", PH7_JSON_ERROR_STATE_MISMATCH_Const}, - {"JSON_ERROR_CTRL_CHAR", PH7_JSON_ERROR_CTRL_CHAR_Const}, - {"JSON_ERROR_SYNTAX", PH7_JSON_ERROR_SYNTAX_Const}, - {"JSON_ERROR_UTF8", PH7_JSON_ERROR_UTF8_Const} -}; - -static const ph7_builtin_func jsonFuncList[] = { - {"json_encode", vm_builtin_json_encode }, - {"json_last_error", vm_builtin_json_last_error}, - {"json_decode", vm_builtin_json_decode } -}; - #endif