Files
Aer/modules/json/json.c
T
2026-11-22 14:53:55 +01:00

3186 lines
114 KiB
C

/**
* @PROJECT AerScript Interpreter
* @COPYRIGHT See COPYING in the top level directory
* @FILE modules/json/json.c
* @DESCRIPTION Typed JSON DOM module for AerScript Interpreter
* @DEVELOPERS Symisc Systems <devel@symisc.net>
* Rafal Kupiec <belliash@codingworkshop.eu.org>
*/
#include <math.h>
#include <locale.h>
#include <string.h>
#include "json.h"
#ifdef __WINNT__
#include <float.h>
#endif
/* 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"
#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]);
}
PH7_ClassInstanceUnref(pInst);
PH7_VmMemoryError(pVm);
return PH7_ABORT;
}
}
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;
}
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");
if(pLocale == (_locale_t)0) {
return SXERR_ABORT;
}
#else
locale_t pLocale, pOld;
pLocale = newlocale(LC_NUMERIC_MASK, "C", (locale_t)0);
if(pLocale == (locale_t)0) {
return SXERR_ABORT;
}
pOld = uselocale(pLocale);
if(pOld == (locale_t)0) {
freelocale(pLocale);
return SXERR_ABORT;
}
#endif
for(nPrec = 15; nPrec < 18; ++nPrec) {
#ifdef __WINNT__
nByte = _snprintf_l(zBuf, (size_t)nBufSize, "%.*g", pLocale, nPrec, (double)rVal);
#else
nByte = snprintf(zBuf, (size_t)nBufSize, "%.*g", nPrec, (double)rVal);
#endif
if(nByte < 0 || (sxu32)nByte >= nBufSize) {
break;
}
#ifdef __WINNT__
if(_strtod_l(zBuf, &zEnd, pLocale) == (double)rVal && zEnd[0] == '\0') {
#else
if(strtod_l(zBuf, &zEnd, pLocale) == (double)rVal && zEnd[0] == '\0') {
#endif
rc = SXRET_OK;
break;
}
}
#ifdef __WINNT__
_free_locale(pLocale);
#else
if(uselocale(pOld) == (locale_t)0) {
return SXERR_ABORT;
}
freelocale(pLocale);
#endif
return rc;
}
/* 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 || zText[0] < '0' || zText[0] > '9') {
return SXERR_SYNTAX;
}
if(zText[0] == '0') {
zText++;
if(zText < zEnd && zText[0] >= '0' && zText[0] <= '9') {
return SXERR_SYNTAX;
}
} else {
while(zText < zEnd && zText[0] >= '0' && zText[0] <= '9') {
zText++;
}
}
if(zText < zEnd && zText[0] == '.') {
zText++;
if(zText >= zEnd || zText[0] < '0' || zText[0] > '9') {
return SXERR_SYNTAX;
}
while(zText < zEnd && zText[0] >= '0' && zText[0] <= '9') {
zText++;
}
}
if(zText < zEnd && (zText[0] == 'e' || zText[0] == 'E')) {
zText++;
if(zText < zEnd && (zText[0] == '+' || zText[0] == '-')) {
zText++;
}
if(zText >= zEnd || zText[0] < '0' || zText[0] > '9') {
return SXERR_SYNTAX;
}
while(zText < zEnd && zText[0] >= '0' && zText[0] <= '9') {
zText++;
}
}
pStream->zText = zText;
return SXRET_OK;
}
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) {
return SXERR_EOF;
}
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] == ',') {
c = pStream->zText[0];
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;
}
pStream->zText++;
} else if(pStream->zText[0] == '"') {
pStream->zText++;
pStr->zString = (const char *)pStream->zText;
while(pStream->zText < pStream->zEnd) {
c = pStream->zText[0];
if(c == '"') {
break;
}
if((unsigned char)c < 0x20) {
pLex->iErr = JSON_ERROR_CTRL_CHAR;
return SXERR_ABORT;
}
if(c == '\\') {
pStream->zText++;
if(pStream->zText >= pStream->zEnd) {
pLex->iErr = JSON_ERROR_SYNTAX;
return SXERR_ABORT;
}
}
pStream->zText++;
}
if(pStream->zText >= pStream->zEnd) {
pLex->iErr = JSON_ERROR_SYNTAX;
return SXERR_ABORT;
}
pToken->nType = JSON_TK_STR;
pStream->zText++;
} else if(pStream->zText[0] == '-' || (pStream->zText[0] >= '0' && pStream->zText[0] <= '9')) {
if(VmJsonScanNumber(pStream) != SXRET_OK) {
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) {
pToken->nType = JSON_TK_TRUE;
pStream->zText += sizeof("true") - 1;
} else if(XLEX_IN_LEN(pStream) >= sizeof("false") - 1 &&
SyStrncmp((const char *)pStream->zText, "false", sizeof("false") - 1) == 0) {
pToken->nType = JSON_TK_FALSE;
pStream->zText += sizeof("false") - 1;
} else if(XLEX_IN_LEN(pStream) >= sizeof("null") - 1 &&
SyStrncmp((const char *)pStream->zText, "null", sizeof("null") - 1) == 0) {
pToken->nType = JSON_TK_NULL;
pStream->zText += sizeof("null") - 1;
} else {
pToken->nType = JSON_TK_INVALID;
pLex->iErr = JSON_ERROR_SYNTAX;
return SXERR_ABORT;
}
pStr->nByte = (sxu32)((const char *)pStream->zText - pStr->zString);
if(pToken->nType == JSON_TK_STR) {
pStr->nByte--;
}
return SXRET_OK;
}
/* ------------------------------------------------------------------ */
/* String dequoting + UTF-8 validation */
/* ------------------------------------------------------------------ */
static sxi32 VmJsonHex4(const unsigned char *zIn, sxu32 *pVal) {
sxu32 iVal = 0, i;
sxi32 c;
for(i = 0 ; i < 4 ; ++i) {
c = SyHexToint(zIn[i]);
if(c < 0) {
return SXERR_SYNTAX;
}
iVal = (iVal << 4) | (sxu32)c;
}
*pVal = iVal;
return SXRET_OK;
}
static void VmJsonAppendCodePoint(ph7_value *pWorker, sxu32 iCode) {
char zBuf[4];
sxu32 nByte;
if(iCode < 0x80) {
zBuf[0] = (char)iCode; nByte = 1;
} else if(iCode < 0x800) {
zBuf[0] = (char)(0xC0 | (iCode >> 6));
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;
} 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;
}
(void)ph7_value_string(pWorker, zBuf, (int)nByte);
}
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;
(void)ph7_value_string(pWorker, "", 0);
while(zIn < zEnd) {
if(zIn[0] == '\\') {
zIn++;
if(zIn >= zEnd) {
*pErr = JSON_ERROR_SYNTAX;
return SXERR_ABORT;
}
c = zIn[0];
zIn++;
switch(c) {
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;
return SXERR_ABORT;
}
zIn += 4;
if(iCode >= 0xD800 && iCode <= 0xDBFF) {
if((zEnd - zIn) < 6 || zIn[0] != '\\' || zIn[1] != 'u'
|| VmJsonHex4(&zIn[2], &iLow) != SXRET_OK
|| iLow < 0xDC00 || iLow > 0xDFFF) {
*pErr = JSON_ERROR_SYNTAX;
return SXERR_ABORT;
}
zIn += 6;
iCode = 0x10000 + ((iCode - 0xD800) << 10) + (iLow - 0xDC00);
} else if(iCode >= 0xDC00 && iCode <= 0xDFFF) {
*pErr = JSON_ERROR_SYNTAX;
return SXERR_ABORT;
}
VmJsonAppendCodePoint(pWorker, iCode);
break;
default:
*pErr = JSON_ERROR_SYNTAX;
return SXERR_ABORT;
}
} else if(zIn[0] < 0x20) {
*pErr = JSON_ERROR_CTRL_CHAR;
return SXERR_ABORT;
} else {
zCur = zIn;
while(zIn < zEnd && zIn[0] != '\\' && zIn[0] >= 0x20) {
zIn++;
}
(void)ph7_value_string(pWorker, (const char *)zCur, (int)(zIn - zCur));
}
}
return SXRET_OK;
}
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, i;
int bReal = 0;
for(i = 0 ; i < nByte ; ++i) {
if(zNum[i] == '.' || zNum[i] == 'e' || zNum[i] == 'E') {
bReal = 1;
break;
}
}
if(bReal == 0) {
sxi32 bNeg = 0, bOverflow = 0;
sxu64 uVal = 0, uLimit;
sxi64 iVal;
i = 0;
if(zNum[0] == '-') { bNeg = 1; i++; }
uLimit = bNeg ? 9223372036854775808ULL : 9223372036854775807ULL;
for(; i < nByte ; ++i) {
sxu32 iDigit = (sxu32)(zNum[i] - '0');
if(uVal > (uLimit - iDigit) / 10) {
bOverflow = 1;
break;
}
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;
} else {
iVal = (sxi64)uVal;
}
JsonFieldSetInt(pNode, "intValue", iVal);
JsonFieldSetDouble(pNode, "realValue", (double)iVal);
JsonFieldSetStr(pNode, "rawNumber", zNum, (int)nByte);
*ppNode = pNode;
return PH7_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;
}
}
{
ph7_value *pNode = JsonNewNode(pCtx, JCLS_NUMBER, JSON_NODE_NUMBER, zPath);
int rc;
if(pNode == 0) {
return PH7_ABORT;
}
rc = JsonNumberFromLexeme(pCtx, pNode, zNum, nByte, zPath);
if(rc != PH7_OK) {
return rc;
}
JsonFieldSetStr(pNode, "rawNumber", zNum, (int)nByte);
*ppNode = pNode;
return PH7_OK;
}
}
/* ------------------------------------------------------------------ */
/* 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;
}
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);
}
} else {
rc = SyBlobAppend(&pP->path, "[", 1);
if(rc == SXRET_OK) {
rc = JsonBlobAppendInt(&pP->path, nIndex);
}
if(rc == SXRET_OK) {
rc = SyBlobAppend(&pP->path, "]", 1);
}
}
if(rc == SXRET_OK) {
rc = SyBlobAppend(&pP->path, "\0", 1);
}
return rc;
}
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));
}
/* 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_opt sOpt;
json_lex sLex;
json_parse sParse;
SySet sToken;
SyLex sLx;
ph7_value *pRoot = 0;
int rc;
rc = JsonOptLoad(pCtx, pOptions, &sOpt);
if(rc != PH7_OK) {
return rc;
}
if(nByte < 1) {
return JsonThrow(pCtx, JSON_ERROR_SYNTAX, "Syntax error", 0, 0, "$");
}
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;
}
SySetInit(&sToken, &pVm->sAllocator, sizeof(SyToken));
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;
}
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);
SyBlobRelease(&sParse.path);
return rc;
}
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", "$");
}
SyLexRelease(&sLx);
SySetRelease(&sToken);
SyBlobRelease(&sParse.path);
if(rc != PH7_OK) {
return rc;
}
*ppRoot = pRoot;
return PH7_OK;
}
/* ------------------------------------------------------------------ */
/* 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;
return JsonRegisterClasses(pVm);
}