From 3202593872e7e51eb564ff96b3d53a2c76b813ac Mon Sep 17 00:00:00 2001 From: Rafal Kupiec Date: Sun, 22 Nov 2026 00:33:56 +0100 Subject: [PATCH] Migrate XML module to typed OOP SAX API --- modules/xml/lib.c | 68 +- modules/xml/lib.h | 7 +- modules/xml/xml.c | 2241 +++++++++++++++++++-------------------------- modules/xml/xml.h | 176 +--- 4 files changed, 1025 insertions(+), 1467 deletions(-) diff --git a/modules/xml/lib.c b/modules/xml/lib.c index f2fe84f..2407d34 100644 --- a/modules/xml/lib.c +++ b/modules/xml/lib.c @@ -646,7 +646,7 @@ static sxi32 XMLExtractNS(SyXMLParser *pParse, SyToken *pToken, SyXMLRawStrNS *p sPrefix.nByte = nOfft; sPrefix.nLine = pTag->nLine; pTag->zString += nOfft + 1; - pTag->nByte -= nOfft; + pTag->nByte -= nOfft + 1; if(pTag->nByte < 1) { if(pParse->xError) { rc = pParse->xError("Missing tag name", SXML_ERROR_SYNTAX, pToken, pParse->pUserData); @@ -709,6 +709,7 @@ static sxi32 ProcessXML(SyXMLParser *pParse, SySet *pTagStack, SySet *pWorker) SySet *pTokenSet = &pParse->sToken; SyXMLRawStrNS sEntry; SyXMLRawStr sNs; + SyXMLRawStr sPrefix; SyToken *pToken; int bGotTag; sxi32 rc; @@ -725,8 +726,9 @@ static sxi32 ProcessXML(SyXMLParser *pParse, SySet *pTagStack, SySet *pWorker) while(SXRET_OK == (SySetGetNextEntry(&(*pTokenSet), (void **)&pToken))) { SyZero(&sEntry, sizeof(SyXMLRawStrNS)); SyZero(&sNs, sizeof(SyXMLRawStr)); + SyZero(&sPrefix, sizeof(SyXMLRawStr)); SySetInit(&sEntry.sNSset, pParse->pAllocator, sizeof(SyHashEntry *)); - sEntry.nLine = sNs.nLine = pToken->nLine; + sEntry.nLine = sNs.nLine = sPrefix.nLine = pToken->nLine; switch(pToken->nType) { case SXML_TOK_DOCTYPE: if(SySetUsed(pTagStack) > 1 || bGotTag) { @@ -832,6 +834,16 @@ static sxi32 ProcessXML(SyXMLParser *pParse, SySet *pTagStack, SySet *pWorker) } else { /* Invoke the supplied callback if any */ if(pParse->xEndTag) { + sxu32 nOfft; + /* Capture the QName prefix before XMLExtractNS() + * strips it from sEntry.zString. */ + if(SyByteFind(sEntry.zString, sEntry.nByte, ':', &nOfft) == SXRET_OK && nOfft > 0) { + sPrefix.zString = sEntry.zString; + sPrefix.nByte = nOfft; + } else { + sPrefix.zString = ""; + sPrefix.nByte = 0; + } rc = SXRET_OK; if(pParse->nFlags & SXML_ENABLE_NAMESPACE) { /* Extract namespace URI */ @@ -841,7 +853,7 @@ static sxi32 ProcessXML(SyXMLParser *pParse, SySet *pTagStack, SySet *pWorker) } } if(rc == SXRET_OK) { - rc = pParse->xEndTag((SyXMLRawStr *)&sEntry, &sNs, pParse->pUserData); + rc = pParse->xEndTag((SyXMLRawStr *)&sEntry, &sNs, &sPrefix, pParse->pUserData); if(rc == SXERR_ABORT) { return SXERR_ABORT; } @@ -876,6 +888,17 @@ static sxi32 ProcessXML(SyXMLParser *pParse, SySet *pTagStack, SySet *pWorker) /* Extract the tag and it's supplied attribute */ rc = XMLProcessStartTag(pParse, pToken, &sEntry, pWorker, pTagStack); if(rc == SXRET_OK) { + /* Capture the QName prefix before XMLExtractNS() strips it from + * sEntry.zString. The URI itself is forwarded verbatim (it may + * legitimately contain the namespace separator). */ + sxu32 nOfft; + if(SyByteFind(sEntry.zString, sEntry.nByte, ':', &nOfft) == SXRET_OK && nOfft > 0) { + sPrefix.zString = sEntry.zString; + sPrefix.nByte = nOfft; + } else { + sPrefix.zString = ""; + sPrefix.nByte = 0; + } if(pParse->nFlags & SXML_ENABLE_NAMESPACE) { /* Extract namespace URI */ rc = XMLExtractNS(pParse, pToken, &sEntry, &sNs); @@ -884,15 +907,17 @@ static sxi32 ProcessXML(SyXMLParser *pParse, SySet *pTagStack, SySet *pWorker) if(rc == SXRET_OK) { /* Invoke the supplied callback */ if(pParse->xStartTag) { - rc = pParse->xStartTag((SyXMLRawStr *)&sEntry, &sNs, SySetUsed(pWorker), - (SyXMLRawStr *)SySetBasePtr(pWorker), pParse->pUserData); + rc = pParse->xStartTag((SyXMLRawStr *)&sEntry, &sNs, &sPrefix, SySetUsed(pWorker), + (SyXMLRawStr *)SySetBasePtr(pWorker), + pToken->nType == SXML_TOK_START_END ? TRUE : FALSE, + pParse->pUserData); if(rc == SXERR_ABORT) { return SXERR_ABORT; } } if(pToken->nType == SXML_TOK_START_END) { if(pParse->xEndTag) { - rc = pParse->xEndTag((SyXMLRawStr *)&sEntry, &sNs, pParse->pUserData); + rc = pParse->xEndTag((SyXMLRawStr *)&sEntry, &sNs, &sPrefix, pParse->pUserData); if(rc == SXERR_ABORT) { return SXERR_ABORT; } @@ -1000,20 +1025,31 @@ PH7_PRIVATE sxi32 SyXMLProcess(SyXMLParser *pParser, const char *zInput, sxu32 n /* Process XML Tokens */ rc = ProcessXML(&(*pParser), &sTagStack, &sWorker); if(pParser->nFlags & SXML_ENABLE_NAMESPACE) { + SyXMLRawStrNS *pTag; + SyHashEntry *pNs; + /* Tags still open after an abort own their declaration-list buffer. + * XMLnsUnlink() already released the buffers of closed tags. */ if(SySetUsed(&sTagStack) > 0) { - SyXMLRawStrNS *pEntry; - SyHashEntry **apEntry; - sxu32 n; SySetResetCursor(&sTagStack); - while(SySetGetNextEntry(&sTagStack, (void **)&pEntry) == SXRET_OK) { - /* Release namespace entries */ - apEntry = (SyHashEntry **)SySetBasePtr(&pEntry->sNSset); - for(n = 0 ; n < SySetUsed(&pEntry->sNSset) ; ++n) { - SyMemBackendFree(pParser->pAllocator, apEntry[n]->pUserData); - } - SySetRelease(&pEntry->sNSset); + while(SySetGetNextEntry(&sTagStack, (void **)&pTag) == SXRET_OK) { + SySetRelease(&pTag->sNSset); } } + /* Single ownership point for the namespace hash: every declaration + * still present here was inserted by XMLProcessNamesSpace() and owns + * a heap SyXMLRawStr. XMLnsUnlink() already removed closed ones, so + * on the normal path this loop is a no-op. On an abort it removes + * the remaining entries *and* frees their payload exactly once -- + * leaving stale keys/payloads would make a later Parse() on the same + * reader read freed memory in XMLExtractNS(). SyHashGetNextEntry() + * advances the cursor before returning, so deleting the entry here + * is safe. */ + SyHashResetLoopCursor(&pParser->hns); + while((pNs = SyHashGetNextEntry(&pParser->hns)) != 0) { + void *pUserData = pNs->pUserData; + SyHashDeleteEntry2(pNs); + SyMemBackendFree(pParser->pAllocator, pUserData); + } } } /* Clean-up the mess left behind */ diff --git a/modules/xml/lib.h b/modules/xml/lib.h index aadd423..ef46ec9 100644 --- a/modules/xml/lib.h +++ b/modules/xml/lib.h @@ -94,9 +94,12 @@ struct SyXMLRawStrNS { /* * Event callback signatures. */ -typedef sxi32(*ProcXMLStartTagHandler)(SyXMLRawStr *, SyXMLRawStr *, sxu32, SyXMLRawStr *, void *); +/* pPrefix carries the QName prefix (empty for no prefix); bEmpty is TRUE for + * so the consumer can distinguish it from . The end-tag + * handler receives the same pPrefix, captured before the prefix is stripped. */ +typedef sxi32(*ProcXMLStartTagHandler)(SyXMLRawStr *, SyXMLRawStr *, SyXMLRawStr *, sxu32, SyXMLRawStr *, int, void *); typedef sxi32(*ProcXMLTextHandler)(SyXMLRawStr *, void *); -typedef sxi32(*ProcXMLEndTagHandler)(SyXMLRawStr *, SyXMLRawStr *, void *); +typedef sxi32(*ProcXMLEndTagHandler)(SyXMLRawStr *, SyXMLRawStr *, SyXMLRawStr *, void *); typedef sxi32(*ProcXMLPIHandler)(SyXMLRawStr *, SyXMLRawStr *, void *); typedef sxi32(*ProcXMLDoctypeHandler)(SyXMLRawStr *, void *); typedef sxi32(*ProcXMLSyntaxErrorHandler)(const char *, int, SyToken *, void *); diff --git a/modules/xml/xml.c b/modules/xml/xml.c index 5214894..0c756c3 100644 --- a/modules/xml/xml.c +++ b/modules/xml/xml.c @@ -2,1489 +2,1092 @@ * @PROJECT AerScript Interpreter * @COPYRIGHT See COPYING in the top level directory * @FILE modules/xml/xml.c - * @DESCRIPTION XML parser module for AerScript Interpreter + * @DESCRIPTION Typed XML SAX module for AerScript Interpreter * @DEVELOPERS Symisc Systems * Rafal Kupiec */ +#include +#include #include "xml.h" /* - * XML_ERROR_NONE - * Expand the value of SXML_ERROR_NO_MEMORY defined in ph7Int.h + * Security note: the underlying SAX engine never resolves external entities + * and installs no entity handlers. OnDoctype therefore exists solely so a + * host can apply a DTD policy: returning PH7_ABORT from the callback stops + * the document before the remainder is parsed (see lib.c ProcessXML). The + * internal subset is only recognised when '[' is the LAST non-whitespace + * character on the DOCTYPE line (immediately before the line break): the + * lexer stops scanning that line at '>' and records the last non-space byte. + * An inline subset such as ]> is truncated at + * the first '>' and rejected. This is a pre-existing engine limitation. */ -static void PH7_XML_ERROR_NONE_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_NO_MEMORY); -} -/* - * XML_ERROR_NO_MEMORY - * Expand the value of SXML_ERROR_NONE defined in ph7Int.h - */ -static void PH7_XML_ERROR_NO_MEMORY_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_NO_MEMORY); -} -/* - * XML_ERROR_SYNTAX - * Expand the value of SXML_ERROR_SYNTAX defined in ph7Int.h - */ -static void PH7_XML_ERROR_SYNTAX_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_SYNTAX); -} -/* - * XML_ERROR_NO_ELEMENTS - * Expand the value of SXML_ERROR_NO_ELEMENTS defined in ph7Int.h - */ -static void PH7_XML_ERROR_NO_ELEMENTS_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_NO_ELEMENTS); -} -/* - * XML_ERROR_INVALID_TOKEN - * Expand the value of SXML_ERROR_INVALID_TOKEN defined in ph7Int.h - */ -static void PH7_XML_ERROR_INVALID_TOKEN_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_INVALID_TOKEN); -} -/* - * XML_ERROR_UNCLOSED_TOKEN - * Expand the value of SXML_ERROR_UNCLOSED_TOKEN defined in ph7Int.h - */ -static void PH7_XML_ERROR_UNCLOSED_TOKEN_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_UNCLOSED_TOKEN); -} -/* - * XML_ERROR_PARTIAL_CHAR - * Expand the value of SXML_ERROR_PARTIAL_CHAR defined in ph7Int.h - */ -static void PH7_XML_ERROR_PARTIAL_CHAR_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_PARTIAL_CHAR); -} -/* - * XML_ERROR_TAG_MISMATCH - * Expand the value of SXML_ERROR_TAG_MISMATCH defined in ph7Int.h - */ -static void PH7_XML_ERROR_TAG_MISMATCH_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_TAG_MISMATCH); -} -/* - * XML_ERROR_DUPLICATE_ATTRIBUTE - * Expand the value of SXML_ERROR_DUPLICATE_ATTRIBUTE defined in ph7Int.h - */ -static void PH7_XML_ERROR_DUPLICATE_ATTRIBUTE_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_DUPLICATE_ATTRIBUTE); -} -/* - * XML_ERROR_JUNK_AFTER_DOC_ELEMENT - * Expand the value of SXML_ERROR_JUNK_AFTER_DOC_ELEMENT defined in ph7Int.h - */ -static void PH7_XML_ERROR_JUNK_AFTER_DOC_ELEMENT_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_JUNK_AFTER_DOC_ELEMENT); -} -/* - * XML_ERROR_PARAM_ENTITY_REF - * Expand the value of SXML_ERROR_PARAM_ENTITY_REF defined in ph7Int.h - */ -static void PH7_XML_ERROR_PARAM_ENTITY_REF_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_PARAM_ENTITY_REF); -} -/* - * XML_ERROR_UNDEFINED_ENTITY - * Expand the value of SXML_ERROR_UNDEFINED_ENTITY defined in ph7Int.h - */ -static void PH7_XML_ERROR_UNDEFINED_ENTITY_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_UNDEFINED_ENTITY); -} -/* - * XML_ERROR_RECURSIVE_ENTITY_REF - * Expand the value of SXML_ERROR_RECURSIVE_ENTITY_REF defined in ph7Int.h - */ -static void PH7_XML_ERROR_RECURSIVE_ENTITY_REF_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_RECURSIVE_ENTITY_REF); -} -/* - * XML_ERROR_ASYNC_ENTITY - * Expand the value of SXML_ERROR_ASYNC_ENTITY defined in ph7Int.h - */ -static void PH7_XML_ERROR_ASYNC_ENTITY_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_ASYNC_ENTITY); -} -/* - * XML_ERROR_BAD_CHAR_REF - * Expand the value of SXML_ERROR_BAD_CHAR_REF defined in ph7Int.h - */ -static void PH7_XML_ERROR_BAD_CHAR_REF_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_BAD_CHAR_REF); -} -/* - * XML_ERROR_BINARY_ENTITY_REF - * Expand the value of SXML_ERROR_BINARY_ENTITY_REF defined in ph7Int.h - */ -static void PH7_XML_ERROR_BINARY_ENTITY_REF_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_BINARY_ENTITY_REF); -} -/* - * XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF - * Expand the value of SXML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF defined in ph7Int.h - */ -static void PH7_XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF); -} -/* - * XML_ERROR_MISPLACED_XML_PI - * Expand the value of SXML_ERROR_MISPLACED_XML_PI defined in ph7Int.h - */ -static void PH7_XML_ERROR_MISPLACED_XML_PI_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_MISPLACED_XML_PI); -} -/* - * XML_ERROR_UNKNOWN_ENCODING - * Expand the value of SXML_ERROR_UNKNOWN_ENCODING defined in ph7Int.h - */ -static void PH7_XML_ERROR_UNKNOWN_ENCODING_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_UNKNOWN_ENCODING); -} -/* - * XML_ERROR_INCORRECT_ENCODING - * Expand the value of SXML_ERROR_INCORRECT_ENCODING defined in ph7Int.h - */ -static void PH7_XML_ERROR_INCORRECT_ENCODING_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_INCORRECT_ENCODING); -} -/* - * XML_ERROR_UNCLOSED_CDATA_SECTION - * Expand the value of SXML_ERROR_UNCLOSED_CDATA_SECTION defined in ph7Int.h - */ -static void PH7_XML_ERROR_UNCLOSED_CDATA_SECTION_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_UNCLOSED_CDATA_SECTION); -} -/* - * XML_ERROR_EXTERNAL_ENTITY_HANDLING - * Expand the value of SXML_ERROR_EXTERNAL_ENTITY_HANDLING defined in ph7Int.h - */ -static void PH7_XML_ERROR_EXTERNAL_ENTITY_HANDLING_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_ERROR_EXTERNAL_ENTITY_HANDLING); -} -/* - * XML_OPTION_CASE_FOLDING - * Expand the value of SXML_OPTION_CASE_FOLDING defined in ph7Int.h. - */ -static void PH7_XML_OPTION_CASE_FOLDING_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_OPTION_CASE_FOLDING); -} -/* - * XML_OPTION_TARGET_ENCODING - * Expand the value of SXML_OPTION_TARGET_ENCODING defined in ph7Int.h. - */ -static void PH7_XML_OPTION_TARGET_ENCODING_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_OPTION_TARGET_ENCODING); -} -/* - * XML_OPTION_SKIP_TAGSTART - * Expand the value of SXML_OPTION_SKIP_TAGSTART defined in ph7Int.h. - */ -static void PH7_XML_OPTION_SKIP_TAGSTART_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_OPTION_SKIP_TAGSTART); -} -/* - * XML_OPTION_SKIP_WHITE - * Expand the value of SXML_OPTION_SKIP_TAGSTART defined in ph7Int.h. - */ -static void PH7_XML_OPTION_SKIP_WHITE_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_int(pVal, SXML_OPTION_SKIP_WHITE); -} -/* - * XML_SAX_IMPL. - * Expand the name of the underlying XML engine. - */ -static void PH7_XML_SAX_IMP_Const(ph7_value *pVal, void *pUserData) { - SXUNUSED(pUserData); /* cc warning */ - ph7_value_string(pVal, "Symisc XML engine", (int)sizeof("Symisc XML engine") - 1); -} -/* - * Allocate and initialize an XML engine. - */ +/* ------------------------------------------------------------------ */ +/* Engine lifetime */ +/* ------------------------------------------------------------------ */ static ph7_xml_engine *VmCreateXMLEngine(ph7_context *pCtx, int process_ns, int ns_sep) { ph7_xml_engine *pEngine; ph7_vm *pVm = pCtx->pVm; - ph7_value *pValue; sxu32 n; - /* Allocate a new instance */ pEngine = (ph7_xml_engine *)SyMemBackendAlloc(&pVm->sAllocator, sizeof(ph7_xml_engine)); if(pEngine == 0) { - /* Out of memory */ return 0; } - /* Zero the structure */ SyZero(pEngine, sizeof(ph7_xml_engine)); - /* Initialize fields */ pEngine->pVm = pVm; pEngine->pCtx = 0; pEngine->ns_sep = ns_sep; SyXMLParserInit(&pEngine->sParser, &pVm->sAllocator, process_ns ? SXML_ENABLE_NAMESPACE : 0); SyBlobInit(&pEngine->sErr, &pVm->sAllocator); PH7_MemObjInit(pVm, &pEngine->sParserValue); + PH7_MemObjInit(pVm, &pEngine->sReaderValue); + PH7_MemObjInit(pVm, &pEngine->sHandler); + PH7_MemObjInit(pVm, &pEngine->sAttrs); + PH7_MemObjInit(pVm, &pEngine->sLocalName); + PH7_MemObjInit(pVm, &pEngine->sNsUri); + PH7_MemObjInit(pVm, &pEngine->sPrefix); for(n = 0 ; n < SX_ARRAYSIZE(pEngine->aCB) ; ++n) { - pValue = &pEngine->aCB[n]; - /* NULLIFY the array entries,until someone register an event handler */ - PH7_MemObjInit(&(*pVm), pValue); + PH7_MemObjInit(pVm, &pEngine->aCB[n]); } ph7_value_resource(&pEngine->sParserValue, pEngine); pEngine->iErrCode = SXML_ERROR_NONE; - /* Finally set the magic number */ pEngine->nMagic = XML_ENGINE_MAGIC; return pEngine; } -/* - * Release an XML engine. - */ static void VmReleaseXMLEngine(ph7_xml_engine *pEngine) { ph7_vm *pVm = pEngine->pVm; - ph7_value *pValue; sxu32 n; - /* Release fields */ SyBlobRelease(&pEngine->sErr); SyXMLParserRelease(&pEngine->sParser); PH7_MemObjRelease(&pEngine->sParserValue); + PH7_MemObjRelease(&pEngine->sReaderValue); + PH7_MemObjRelease(&pEngine->sHandler); + PH7_MemObjRelease(&pEngine->sAttrs); + PH7_MemObjRelease(&pEngine->sLocalName); + PH7_MemObjRelease(&pEngine->sNsUri); + PH7_MemObjRelease(&pEngine->sPrefix); for(n = 0 ; n < SX_ARRAYSIZE(pEngine->aCB) ; ++n) { - pValue = &pEngine->aCB[n]; - PH7_MemObjRelease(pValue); + PH7_MemObjRelease(&pEngine->aCB[n]); } pEngine->nMagic = 0x2621; - /* Finally,release the whole instance */ SyMemBackendFree(&pVm->sAllocator, pEngine); } -/* - * resource xml_parser_create([ string $encoding ]) - * Create an UTF-8 XML parser. - * Parameter - * $encoding - * (Only UTF-8 encoding is used) - * Return - * Returns a resource handle for the new XML parser. - */ -static int vm_builtin_xml_parser_create(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - /* Allocate a new instance */ - pEngine = VmCreateXMLEngine(&(*pCtx), 0, ':'); - if(pEngine == 0) { - PH7_VmMemoryError(pCtx->pVm); - /* Return null */ - ph7_result_null(pCtx); - SXUNUSED(nArg); /* cc warning */ - SXUNUSED(apArg); - return PH7_OK; +/* Replace an owned string slot with a snapshot of the SAX raw text. */ +static void XmlSetString(ph7_xml_engine *pEngine, ph7_value *pSlot, const char *zString, int nByte) { + PH7_MemObjRelease(pSlot); + PH7_MemObjInit(pEngine->pVm, pSlot); + if(zString == 0) { + zString = ""; + nByte = 0; } - /* Return the engine as a resource */ - ph7_result_resource(pCtx, pEngine); - return PH7_OK; + if(nByte < 0) { + nByte = 0; + } + ph7_value_string(pSlot, zString, nByte); } -/* - * resource xml_parser_create_ns([ string $encoding[,string $separator = ':']]) - * Create an UTF-8 XML parser with namespace support. - * Parameter - * $encoding - * (Only UTF-8 encoding is supported) - * $separator - * Namespace separator (a single character) - * Return - * Returns a resource handle for the new XML parser. - */ -static int vm_builtin_xml_parser_create_ns(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - int ns_sep = ':'; - if(nArg > 1 && ph7_value_is_string(apArg[1])) { - const char *zSep = ph7_value_to_string(apArg[1], 0); - if(zSep[0] != 0) { - ns_sep = zSep[0]; +/* Capture line/byte-offset/column of the event's token. Both the engine and + * the raw string point into the same input buffer, so this is valid for the + * whole callback; we store plain integers so it also survives Parse(). */ +static void XmlTrackPos(ph7_xml_engine *pEngine, SyXMLRawStr *pRaw) { + const char *zInput = (const char *)pEngine->sParser.sLex.sStream.zInput; + const char *zEnd = (const char *)pEngine->sParser.sLex.sStream.zEnd; + const char *z = pRaw ? pRaw->zString : 0; + pEngine->nCurLine = pRaw ? pRaw->nLine : 0; + pEngine->iCurByte = 0; + pEngine->nCurCol = 0; + /* Some SAX strings are static literals (e.g. the empty default-namespace + * prefix in lib.c), not slices of the input buffer. Never subtract or scan + * across unrelated allocations. */ + if(zInput == 0 || zEnd == 0 || z == 0 || z < zInput || z > zEnd) { + return; + } + pEngine->iCurByte = (sxi64)(z - zInput); + { + const char *p = z; + while(p > zInput && p[-1] != '\n') { + --p; } + pEngine->nCurCol = (sxu32)(z - p); } - /* Allocate a new instance */ - pEngine = VmCreateXMLEngine(&(*pCtx), TRUE, ns_sep); - if(pEngine == 0) { - PH7_VmMemoryError(pCtx->pVm); - /* Return null */ - ph7_result_null(pCtx); - return PH7_OK; - } - /* Return the engine as a resource */ - ph7_result_resource(pCtx, pEngine); - return PH7_OK; } -/* - * bool xml_parser_free(resource $parser) - * Release an XML engine. - * Parameter - * $parser - * A reference to the XML parser to free. - * Return - * This function returns FALSE if parser does not refer - * to a valid parser, or else it frees the parser and returns TRUE. - */ -static int vm_builtin_xml_parser_free(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; + +/* ------------------------------------------------------------------ */ +/* Callback dispatch */ +/* ------------------------------------------------------------------ */ +static sxi32 XmlPropagate(ph7_xml_engine *pEngine, ph7_value *pResult, sxi32 rc) { + if(rc == PH7_EXCEPTION) { + PH7_VmDeferTransfer(pEngine->pVm, rc, pResult); + } else { + PH7_MemObjRelease(pResult); } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Safely release the engine */ - VmReleaseXMLEngine(pEngine); - /* Return TRUE */ - ph7_result_bool(pCtx, 1); - return PH7_OK; + return rc; } -/* - * bool xml_set_element_handler(resource $parser,callback $start_element_handler,[callback $end_element_handler]) - * Sets the element handler functions for the XML parser. start_element_handler and end_element_handler - * are strings containing the names of functions. - * Parameters - * $parser - * A reference to the XML parser to set up start and end element handler functions. - * $start_element_handler - * The function named by start_element_handler must accept three parameters: - * start_element_handler(resource $parser,string $name,array $attribs) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $name - * The second parameter, name, contains the name of the element for which this handler - * is called.If case-folding is in effect for this parser, the element name will be in uppercase letters. - * $attribs - * The third parameter, attribs, contains an associative array with the element's attributes (if any). - * The keys of this array are the attribute names, the values are the attribute values. - * Attribute names are case-folded on the same criteria as element names.Attribute values are not case-folded. - * The original order of the attributes can be retrieved by walking through attribs the normal way, using each(). - * The first key in the array was the first attribute, and so on. - * Note: Instead of a function name, an array containing an object reference and a method name can also be supplied. - * $end_element_handler - * The function named by end_element_handler must accept two parameters: - * end_element_handler(resource $parser,string $name) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $name - * The second parameter, name, contains the name of the element for which this handler - * is called.If case-folding is in effect for this parser, the element name will be in uppercase - * letters. - * If a handler function is set to an empty string, or FALSE, the handler in question is disabled. - * Return - * TRUE on success or FALSE on failure. - */ -static int vm_builtin_xml_set_element_handler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; +static sxi32 XmlCallHandler(ph7_xml_engine *pEngine, const char *zMethod, + ph7_value **apArg, int nArg) { + ph7_value sResult; + ph7_class_instance *pThis; + ph7_class_method *pMeth; + sxi32 rc; + if(!ph7_value_is_object(&pEngine->sHandler)) { + return SXRET_OK; } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; + pThis = (ph7_class_instance *)pEngine->sHandler.x.pOther; + if(pThis == 0) { + return SXRET_OK; } - if(nArg > 1) { - /* Save the start_element_handler callback for later invocation */ - PH7_MemObjStore(apArg[1]/* User callback*/, &pEngine->aCB[PH7_XML_START_TAG]); - if(nArg > 2) { - /* Save the end_element_handler callback for later invocation */ - PH7_MemObjStore(apArg[2]/* User callback*/, &pEngine->aCB[PH7_XML_END_TAG]); - } + pMeth = PH7_ClassExtractMethod(pThis->pClass, zMethod, (sxu32)SyStrlen(zMethod)); + if(pMeth == 0) { + return SXRET_OK; } - /* All done, return TRUE */ - ph7_result_bool(pCtx, 1); - return PH7_OK; + PH7_MemObjInit(pEngine->pVm, &sResult); + rc = PH7_VmCallClassMethod(pEngine->pVm, pThis, pMeth, &sResult, nArg, apArg); + return XmlPropagate(pEngine, &sResult, rc); } -/* - * bool xml_set_character_data_handler(resource $parser,callback $handler) - * Sets the character data handler function for the XML parser parser. - * Parameters - * $parser - * A reference to the XML parser to set up character data handler function. - * $handler - * handler is a string containing the name of the callback. - * The function named by handler must accept two parameters: - * handler(resource $parser,string $data) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $data - * The second parameter, data, contains the character data as a string. - * Character data handler is called for every piece of a text in the XML document. - * It can be called multiple times inside each fragment (e.g. for non-ASCII strings). - * If a handler function is set to an empty string, or FALSE, the handler in question is disabled. - * Note: Instead of a function name, an array containing an object reference and a method name - * can also be supplied. - * Return - * TRUE on success or FALSE on failure. - */ -static int vm_builtin_xml_set_character_data_handler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; +static sxi32 XmlCallCallback(ph7_xml_engine *pEngine, int nSlot, ph7_value **apArg, int nArg) { + ph7_value *pCallback = &pEngine->aCB[nSlot]; + ph7_value sResult; + sxi32 rc; + if(!PH7_VmIsCallable(pEngine->pVm, pCallback, 0)) { + return SXRET_OK; } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - if(nArg > 1) { - /* Save the user callback for later invocation */ - PH7_MemObjStore(apArg[1]/* User callback*/, &pEngine->aCB[PH7_XML_CDATA]); - } - /* All done, return TRUE */ - ph7_result_bool(pCtx, 1); - return PH7_OK; + PH7_MemObjInit(pEngine->pVm, &sResult); + rc = PH7_VmCallUserFunction(pEngine->pVm, pCallback, nArg, apArg, &sResult); + return XmlPropagate(pEngine, &sResult, rc); } -/* - * bool xml_set_default_handler(resource $parser,callback $handler) - * Set up default handler. - * Parameters - * $parser - * A reference to the XML parser to set up character data handler function. - * $handler - * handler is a string containing the name of the callback. - * The function named by handler must accept two parameters: - * handler(resource $parser,string $data) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $data - * The second parameter, data, contains the character data.This may be the XML declaration - * document type declaration, entities or other data for which no other handler exists. - * Note: Instead of a function name, an array containing an object reference and a method name - * can also be supplied. - * Return - * TRUE on success or FALSE on failure. - */ -static int vm_builtin_xml_set_default_handler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; +/* A typed IXmlHandler wins over a convenience callback; both receive the + * current XmlReader object as their first argument. */ +static sxi32 XmlNotify(ph7_xml_engine *pEngine, int nSlot, const char *zMethod, + ph7_value **apArg, int nArg) { + sxi32 rc; + if(ph7_value_is_object(&pEngine->sHandler)) { + rc = XmlCallHandler(pEngine, zMethod, apArg, nArg); + } else { + rc = XmlCallCallback(pEngine, nSlot, apArg, nArg); } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; + if(rc != PH7_OK) { + pEngine->bAbort = TRUE; /* PH7_ABORT / PH7_EXCEPTION from a user handler */ } - if(nArg > 1) { - /* Save the user callback for later invocation */ - PH7_MemObjStore(apArg[1]/* User callback*/, &pEngine->aCB[PH7_XML_DEF]); - } - /* All done, return TRUE */ - ph7_result_bool(pCtx, 1); - return PH7_OK; + return rc; } -/* - * bool xml_set_end_namespace_decl_handler(resource $parser,callback $handler) - * Set up end namespace declaration handler. - * Parameters - * $parser - * A reference to the XML parser to set up character data handler function. - * $handler - * handler is a string containing the name of the callback. - * The function named by handler must accept two parameters: - * handler(resource $parser,string $prefix) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $prefix - * The prefix is a string used to reference the namespace within an XML object. - * Note: Instead of a function name, an array containing an object reference and a method name - * can also be supplied. - * Return - * TRUE on success or FALSE on failure. - */ -static int vm_builtin_xml_set_end_namespace_decl_handler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - if(nArg > 1) { - /* Save the user callback for later invocation */ - PH7_MemObjStore(apArg[1]/* User callback*/, &pEngine->aCB[PH7_XML_NS_END]); - } - /* All done, return TRUE */ - ph7_result_bool(pCtx, 1); - return PH7_OK; -} -/* - * bool xml_set_start_namespace_decl_handler(resource $parser,callback $handler) - * Set up start namespace declaration handler. - * Parameters - * $parser - * A reference to the XML parser to set up character data handler function. - * $handler - * handler is a string containing the name of the callback. - * The function named by handler must accept two parameters: - * handler(resource $parser,string $prefix,string $uri) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $prefix - * The prefix is a string used to reference the namespace within an XML object. - * $uri - * Uniform Resource Identifier (URI) of namespace. - * Note: Instead of a function name, an array containing an object reference and a method name - * can also be supplied. - * Return - * TRUE on success or FALSE on failure. - */ -static int vm_builtin_xml_set_start_namespace_decl_handler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - if(nArg > 1) { - /* Save the user callback for later invocation */ - PH7_MemObjStore(apArg[1]/* User callback*/, &pEngine->aCB[PH7_XML_NS_START]); - } - /* All done, return TRUE */ - ph7_result_bool(pCtx, 1); - return PH7_OK; -} -/* - * bool xml_set_processing_instruction_handler(resource $parser,callback $handler) - * Set up processing instruction (PI) handler. - * Parameters - * $parser - * A reference to the XML parser to set up character data handler function. - * $handler - * handler is a string containing the name of the callback. - * The function named by handler must accept three parameters: - * handler(resource $parser,string $target,string $data) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $target - * The second parameter, target, contains the PI target. - * $data - The third parameter, data, contains the PI data. - * Note: Instead of a function name, an array containing an object reference and a method name - * can also be supplied. - * Return - * TRUE on success or FALSE on failure. - */ -static int vm_builtin_xml_set_processing_instruction_handler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - if(nArg > 1) { - /* Save the user callback for later invocation */ - PH7_MemObjStore(apArg[1]/* User callback*/, &pEngine->aCB[PH7_XML_PI]); - } - /* All done, return TRUE */ - ph7_result_bool(pCtx, 1); - return PH7_OK; -} -/* - * bool xml_set_unparsed_entity_decl_handler(resource $parser,callback $handler) - * Set up unparsed entity declaration handler. - * Parameters - * $parser - * A reference to the XML parser to set up character data handler function. - * $handler - * handler is a string containing the name of the callback. - * The function named by handler must accept six parameters: - * handler(resource $parser,string $entity_name,string $base,string $system_id,string $public_id,string $notation_name) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $entity_name - * The name of the entity that is about to be defined. - * $base - * This is the base for resolving the system identifier (systemId) of the external entity. - * Currently this parameter will always be set to an empty string. - * $system_id - * System identifier for the external entity. - * $public_id - * Public identifier for the external entity. - * $notation_name - * Name of the notation of this entity (see xml_set_notation_decl_handler()). - * Note: Instead of a function name, an array containing an object reference and a method name - * can also be supplied. - * Return - * TRUE on success or FALSE on failure. - */ -static int vm_builtin_xml_set_unparsed_entity_decl_handler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - if(nArg > 1) { - /* Save the user callback for later invocation */ - PH7_MemObjStore(apArg[1]/* User callback*/, &pEngine->aCB[PH7_XML_UNPED]); - } - /* All done, return TRUE */ - ph7_result_bool(pCtx, 1); - return PH7_OK; -} -/* - * bool xml_set_notation_decl_handler(resource $parser,callback $handler) - * Set up notation declaration handler. - * Parameters - * $parser - * A reference to the XML parser to set up character data handler function. - * $handler - * handler is a string containing the name of the callback. - * The function named by handler must accept five parameters: - * handler(resource $parser,string $entity_name,string $base,string $system_id,string $public_id) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $entity_name - * The name of the entity that is about to be defined. - * $base - * This is the base for resolving the system identifier (systemId) of the external entity. - * Currently this parameter will always be set to an empty string. - * $system_id - * System identifier for the external entity. - * $public_id - * Public identifier for the external entity. - * Note: Instead of a function name, an array containing an object reference and a method name - * can also be supplied. - * Return - * TRUE on success or FALSE on failure. - */ -static int vm_builtin_xml_set_notation_decl_handler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - if(nArg > 1) { - /* Save the user callback for later invocation */ - PH7_MemObjStore(apArg[1]/* User callback*/, &pEngine->aCB[PH7_XML_ND]); - } - /* All done, return TRUE */ - ph7_result_bool(pCtx, 1); - return PH7_OK; -} -/* - * bool xml_set_external_entity_ref_handler(resource $parser,callback $handler) - * Set up external entity reference handler. - * Parameters - * $parser - * A reference to the XML parser to set up character data handler function. - * $handler - * handler is a string containing the name of the callback. - * The function named by handler must accept five parameters: - * handler(resource $parser,string $open_entity_names,string $base,string $system_id,string $public_id) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $open_entity_names - * The second parameter, open_entity_names, is a space-separated list of the names - * of the entities that are open for the parse of this entity (including the name of the referenced entity). - * $base - * This is the base for resolving the system identifier (system_id) of the external entity. - * Currently this parameter will always be set to an empty string. - * $system_id - * The fourth parameter, system_id, is the system identifier as specified in the entity declaration. - * $public_id - * The fifth parameter, public_id, is the public identifier as specified in the entity declaration - * or an empty string if none was specified; the whitespace in the public identifier will have been - * normalized as required by the XML spec. - * Note: Instead of a function name, an array containing an object reference and a method name - * can also be supplied. - * Return - * TRUE on success or FALSE on failure. - */ -static int vm_builtin_xml_set_external_entity_ref_handler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - if(nArg > 1) { - /* Save the user callback for later invocation */ - PH7_MemObjStore(apArg[1]/* User callback*/, &pEngine->aCB[PH7_XML_EER]); - } - /* All done, return TRUE */ - ph7_result_bool(pCtx, 1); - return PH7_OK; -} -/* - * int xml_get_current_line_number(resource $parser) - * Gets the current line number for the given XML parser. - * Parameters - * $parser - * A reference to the XML parser. - * Return - * This function returns FALSE if parser does not refer - * to a valid parser, or else it returns which line the parser - * is currently at in its data buffer. - */ -static int vm_builtin_xml_get_current_line_number(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Return the line number */ - ph7_result_int(pCtx, (int)pEngine->nLine); - return PH7_OK; -} -/* - * int xml_get_current_byte_index(resource $parser) - * Gets the current byte index of the given XML parser. - * Parameters - * $parser - * A reference to the XML parser. - * Return - * This function returns FALSE if parser does not refer to a valid - * parser, or else it returns which byte index the parser is currently - * at in its data buffer (starting at 0). - */ -static int vm_builtin_xml_get_current_byte_index(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - SyStream *pStream; - SyToken *pToken; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the current processed token */ - pToken = (SyToken *)SySetPeekCurrentEntry(&pEngine->sParser.sToken); - if(pToken == 0) { - /* Stream not yet processed */ - ph7_result_int(pCtx, 0); - return 0; - } - /* Point to the input stream */ - pStream = &pEngine->sParser.sLex.sStream; - /* Return the byte index */ - ph7_result_int64(pCtx, (ph7_int64)(pToken->sData.zString - (const char *)pStream->zInput)); - return PH7_OK; -} -/* - * bool xml_set_object(resource $parser,object &$object) - * Use XML Parser within an object. - * NOTE - * This function is deprecated and is a no-op. - * Parameters - * $parser - * A reference to the XML parser. - * $object - * The object where to use the XML parser. - * Return - * Always FALSE. - */ -static int vm_builtin_xml_set_object(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 2 || !ph7_value_is_resource(apArg[0]) || !ph7_value_is_object(apArg[1])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Throw a notice and return */ - PH7_VmThrowError(pCtx->pVm, PH7_CTX_DEPRECATED, "This function is deprecated and is a no-op." - "In order to mimic this behaviour,you can supply instead of a function name an array " - "containing an object reference and a method name." - ); - /* Return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; -} -/* - * int xml_get_current_column_number(resource $parser) - * Gets the current column number of the given XML parser. - * Parameters - * $parser - * A reference to the XML parser. - * Return - * This function returns FALSE if parser does not refer to a valid parser, or else it returns - * which column on the current line (as given by xml_get_current_line_number()) the parser - * is currently at. - */ -static int vm_builtin_xml_get_current_column_number(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - SyStream *pStream; - SyToken *pToken; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the current processed token */ - pToken = (SyToken *)SySetPeekCurrentEntry(&pEngine->sParser.sToken); - if(pToken == 0) { - /* Stream not yet processed */ - ph7_result_int(pCtx, 0); - return 0; - } - /* Point to the input stream */ - pStream = &pEngine->sParser.sLex.sStream; - /* Return the byte index */ - ph7_result_int64(pCtx, (ph7_int64)(pToken->sData.zString - (const char *)pStream->zInput) / 80); - return PH7_OK; -} -/* - * int xml_get_error_code(resource $parser) - * Get XML parser error code. - * Parameters - * $parser - * A reference to the XML parser. - * Return - * This function returns FALSE if parser does not refer to a valid - * parser, or else it returns one of the error codes listed in the error - * codes section. - */ -static int vm_builtin_xml_get_error_code(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - if(nArg < 1 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Return the error code if any */ - ph7_result_int(pCtx, pEngine->iErrCode); - return PH7_OK; -} -/* - * XML parser event callbacks - * Each time the unserlying XML parser extract a single token - * from the input,one of the following callbacks are invoked. - * IMP-XML-ENGINE-07-07-2012 22:02 FreeBSD [chm@symisc.net] - */ -/* - * Create a scalar ph7_value holding the value - * of an XML tag/attribute/CDATA and so on. - */ + +/* ------------------------------------------------------------------ */ +/* SAX values */ +/* ------------------------------------------------------------------ */ static ph7_value *VmXMLValue(ph7_xml_engine *pEngine, SyXMLRawStr *pXML, SyXMLRawStr *pNsUri) { - ph7_value *pValue; - /* Allocate a new scalar variable */ - pValue = ph7_context_new_scalar(pEngine->pCtx); + ph7_value *pValue = ph7_context_new_scalar(pEngine->pCtx); if(pValue == 0) { PH7_VmMemoryError(pEngine->pCtx->pVm); return 0; } if(pNsUri && pNsUri->nByte > 0) { - /* Append namespace URI and the separator */ + /* Dead in the typed API: every caller passes pNsUri == 0. Kept only so + * the reserved ns_sep field remains self-consistent. */ ph7_value_string_format(pValue, "%.*s%c", pNsUri->nByte, pNsUri->zString, pEngine->ns_sep); } - /* Copy the tag value */ ph7_value_string(pValue, pXML->zString, (int)pXML->nByte); return pValue; } -/* - * Create a 'ph7_value' of type array holding the values - * of an XML tag attributes. - */ static ph7_value *VmXMLAttrValue(ph7_xml_engine *pEngine, SyXMLRawStr *aAttr, sxu32 nAttr) { - ph7_value *pArray; - /* Create an empty array */ - pArray = ph7_context_new_array(pEngine->pCtx); + ph7_value *pArray = ph7_context_new_array(pEngine->pCtx); if(pArray == 0) { PH7_VmMemoryError(pEngine->pCtx->pVm); return 0; } if(nAttr > 0) { - ph7_value *pKey, *pValue; + ph7_value *pKey = ph7_context_new_scalar(pEngine->pCtx); + ph7_value *pValue = ph7_context_new_scalar(pEngine->pCtx); sxu32 n; - /* Create worker variables */ - pKey = ph7_context_new_scalar(pEngine->pCtx); - pValue = ph7_context_new_scalar(pEngine->pCtx); if(pKey == 0 || pValue == 0) { PH7_VmMemoryError(pEngine->pCtx->pVm); return 0; } - /* Copy attributes */ for(n = 0 ; n < nAttr ; n += 2) { - /* Reset string cursors */ ph7_value_reset_string_cursor(pKey); ph7_value_reset_string_cursor(pValue); - /* Copy attribute name and it's associated value */ - ph7_value_string(pKey, aAttr[n].zString, (int)aAttr[n].nByte); /* Attribute name */ - ph7_value_string(pValue, aAttr[n + 1].zString, (int)aAttr[n + 1].nByte); /* Attribute value */ - /* Insert in the array */ - ph7_array_add_elem(pArray, pKey, pValue); /* Will make it's own copy */ + ph7_value_string(pKey, aAttr[n].zString, (int)aAttr[n].nByte); + ph7_value_string(pValue, aAttr[n + 1].zString, (int)aAttr[n + 1].nByte); + ph7_array_add_elem(pArray, pKey, pValue); } - /* Release the worker variables */ ph7_context_release_value(pEngine->pCtx, pKey); ph7_context_release_value(pEngine->pCtx, pValue); } - /* Return the freshly created array */ return pArray; } -/* - * Start element handler. - * The user defined callback must accept three parameters: - * start_element_handler(resource $parser,string $name,array $attribs ) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $name - * The second parameter, name, contains the name of the element for which this handler - * is called.If case-folding is in effect for this parser, the element name will be in uppercase letters. - * $attribs - * The third parameter, attribs, contains an associative array with the element's attributes (if any). - * The keys of this array are the attribute names, the values are the attribute values. - * Attribute names are case-folded on the same criteria as element names.Attribute values are not case-folded. - * The original order of the attributes can be retrieved by walking through attribs the normal way, using each(). - * The first key in the array was the first attribute, and so on. - * Note: Instead of a function name, an array containing an object reference and a method name can also be supplied. - */ -static sxi32 VmXMLStartElementHandler(SyXMLRawStr *pStart, SyXMLRawStr *pNS, sxu32 nAttr, SyXMLRawStr *aAttr, void *pUserData) { + +/* ------------------------------------------------------------------ */ +/* SAX event callbacks */ +/* ------------------------------------------------------------------ */ +static sxi32 VmXMLStartElementHandler(SyXMLRawStr *pStart, SyXMLRawStr *pNS, + SyXMLRawStr *pPrefix, sxu32 nAttr, SyXMLRawStr *aAttr, int bEmpty, void *pUserData) { ph7_xml_engine *pEngine = (ph7_xml_engine *)pUserData; - ph7_value *pCallback, *pTag, *pAttr; - /* Point to the target user defined callback */ - pCallback = &pEngine->aCB[PH7_XML_START_TAG]; - /* Make sure the given callback is callable */ - if(!PH7_VmIsCallable(pEngine->pVm, pCallback, 0)) { - /* Not callable, return immediately*/ - return SXRET_OK; - } - /* Create a ph7_value holding the tag name */ - pTag = VmXMLValue(pEngine, pStart, pNS); - /* Create a ph7_value holding the tag attributes */ + ph7_value *apArg[3]; + ph7_value *pTag, *pAttr; + XmlTrackPos(pEngine, pStart); + XmlSetString(pEngine, &pEngine->sLocalName, pStart->zString, (int)pStart->nByte); + XmlSetString(pEngine, &pEngine->sNsUri, pNS ? pNS->zString : 0, pNS ? (int)pNS->nByte : 0); + XmlSetString(pEngine, &pEngine->sPrefix, pPrefix ? pPrefix->zString : 0, pPrefix ? (int)pPrefix->nByte : 0); + pEngine->bEmptyElement = bEmpty ? TRUE : FALSE; + ++pEngine->nDepth; + pTag = VmXMLValue(pEngine, pStart, 0); /* local name only; never glue URI + separator */ pAttr = VmXMLAttrValue(pEngine, aAttr, nAttr); - if(pTag == 0 || pAttr == 0) { - SXUNUSED(pNS); /* cc warning */ - /* Out of mem, return immediately */ + if(pTag == 0 || pAttr == 0) { return SXRET_OK; } - /* Invoke the user callback */ - PH7_VmCallUserFunctionAp(pEngine->pVm, pCallback, 0, &pEngine->sParserValue, pTag, pAttr, 0); - /* Clean-up the mess left behind */ + PH7_MemObjRelease(&pEngine->sAttrs); + PH7_MemObjInit(pEngine->pVm, &pEngine->sAttrs); + (void)PH7_MemObjSnapshot(pAttr, &pEngine->sAttrs); + apArg[0] = &pEngine->sReaderValue; + apArg[1] = pTag; + apArg[2] = pAttr; + (void)XmlNotify(pEngine, PH7_XML_START_TAG, "OnStartElement", apArg, 3); ph7_context_release_value(pEngine->pCtx, pTag); ph7_context_release_value(pEngine->pCtx, pAttr); - return SXRET_OK; + return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } -/* - * End element handler. - * The user defined callback must accept two parameters: - * end_element_handler(resource $parser,string $name) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $name - * The second parameter, name, contains the name of the element for which this handler is called. - * If case-folding is in effect for this parser, the element name will be in uppercase letters. - * Note: Instead of a function name, an array containing an object reference and a method name - * can also be supplied. - */ -static sxi32 VmXMLEndElementHandler(SyXMLRawStr *pEnd, SyXMLRawStr *pNS, void *pUserData) { +static sxi32 VmXMLEndElementHandler(SyXMLRawStr *pEnd, SyXMLRawStr *pNS, + SyXMLRawStr *pPrefix, void *pUserData) { ph7_xml_engine *pEngine = (ph7_xml_engine *)pUserData; - ph7_value *pCallback, *pTag; - /* Point to the target user defined callback */ - pCallback = &pEngine->aCB[PH7_XML_END_TAG]; - /* Make sure the given callback is callable */ - if(!PH7_VmIsCallable(pEngine->pVm, pCallback, 0)) { - /* Not callable, return immediately*/ - return SXRET_OK; + ph7_value *apArg[2]; + ph7_value *pTag; + XmlTrackPos(pEngine, pEnd); + XmlSetString(pEngine, &pEngine->sLocalName, pEnd->zString, (int)pEnd->nByte); + XmlSetString(pEngine, &pEngine->sNsUri, pNS ? pNS->zString : 0, pNS ? (int)pNS->nByte : 0); + XmlSetString(pEngine, &pEngine->sPrefix, pPrefix ? pPrefix->zString : 0, + pPrefix ? (int)pPrefix->nByte : 0); + pEngine->bEmptyElement = FALSE; + if(pEngine->nDepth > 0) { + --pEngine->nDepth; } - /* Create a ph7_value holding the tag name */ - pTag = VmXMLValue(pEngine, pEnd, pNS); + pTag = VmXMLValue(pEngine, pEnd, 0); if(pTag == 0) { - SXUNUSED(pNS); /* cc warning */ - /* Out of mem, return immediately */ return SXRET_OK; } - /* Invoke the user callback */ - PH7_VmCallUserFunctionAp(pEngine->pVm, pCallback, 0, &pEngine->sParserValue, pTag, 0); - /* Clean-up the mess left behind */ + apArg[0] = &pEngine->sReaderValue; + apArg[1] = pTag; + (void)XmlNotify(pEngine, PH7_XML_END_TAG, "OnEndElement", apArg, 2); ph7_context_release_value(pEngine->pCtx, pTag); - return SXRET_OK; + return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } -/* - * Character data handler. - * The user defined callback must accept two parameters: - * handler(resource $parser,string $data) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $data - * The second parameter, data, contains the character data as a string. - * Character data handler is called for every piece of a text in the XML document. - * It can be called multiple times inside each fragment (e.g. for non-ASCII strings). - * If a handler function is set to an empty string, or FALSE, the handler in question is disabled. - * Note: Instead of a function name, an array containing an object reference and a method name can also be supplied. - */ static sxi32 VmXMLTextHandler(SyXMLRawStr *pText, void *pUserData) { ph7_xml_engine *pEngine = (ph7_xml_engine *)pUserData; - ph7_value *pCallback, *pData; - /* Point to the target user defined callback */ - pCallback = &pEngine->aCB[PH7_XML_CDATA]; - /* Make sure the given callback is callable */ - if(!PH7_VmIsCallable(pEngine->pVm, pCallback, 0)) { - /* Not callable, return immediately*/ - return SXRET_OK; - } - /* Create a ph7_value holding the data */ - pData = VmXMLValue(pEngine, &(*pText), 0); + ph7_value *apArg[2]; + ph7_value *pData; + XmlTrackPos(pEngine, pText); + pData = VmXMLValue(pEngine, pText, 0); if(pData == 0) { - /* Out of mem, return immediately */ return SXRET_OK; } - /* Invoke the user callback */ - PH7_VmCallUserFunctionAp(pEngine->pVm, pCallback, 0, &pEngine->sParserValue, pData, 0); - /* Clean-up the mess left behind */ + apArg[0] = &pEngine->sReaderValue; + apArg[1] = pData; + (void)XmlNotify(pEngine, PH7_XML_CDATA, "OnText", apArg, 2); ph7_context_release_value(pEngine->pCtx, pData); - return SXRET_OK; + return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } -/* - * Processing instruction (PI) handler. - * The user defined callback must accept two parameters: - * handler(resource $parser,string $target,string $data) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $target - * The second parameter, target, contains the PI target. - * $data - * The third parameter, data, contains the PI data. - * Note: Instead of a function name, an array containing an object reference - * and a method name can also be supplied. - */ static sxi32 VmXMLPIHandler(SyXMLRawStr *pTargetStr, SyXMLRawStr *pDataStr, void *pUserData) { ph7_xml_engine *pEngine = (ph7_xml_engine *)pUserData; - ph7_value *pCallback, *pTarget, *pData; - /* Point to the target user defined callback */ - pCallback = &pEngine->aCB[PH7_XML_PI]; - /* Make sure the given callback is callable */ - if(!PH7_VmIsCallable(pEngine->pVm, pCallback, 0)) { - /* Not callable, return immediately*/ - return SXRET_OK; - } - /* Get a ph7_value holding the data */ - pTarget = VmXMLValue(pEngine, &(*pTargetStr), 0); - pData = VmXMLValue(pEngine, &(*pDataStr), 0); + ph7_value *apArg[3]; + ph7_value *pTarget, *pData; + XmlTrackPos(pEngine, pTargetStr); + pTarget = VmXMLValue(pEngine, pTargetStr, 0); + pData = VmXMLValue(pEngine, pDataStr, 0); if(pTarget == 0 || pData == 0) { - /* Out of mem, return immediately */ return SXRET_OK; } - /* Invoke the user callback */ - PH7_VmCallUserFunctionAp(pEngine->pVm, pCallback, 0, &pEngine->sParserValue, pTarget, pData, 0); - /* Clean-up the mess left behind */ + apArg[0] = &pEngine->sReaderValue; + apArg[1] = pTarget; + apArg[2] = pData; + (void)XmlNotify(pEngine, PH7_XML_PI, "OnProcessingInstruction", apArg, 3); ph7_context_release_value(pEngine->pCtx, pTarget); ph7_context_release_value(pEngine->pCtx, pData); - return SXRET_OK; + return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } -/* - * Namespace declaration handler. - * The user defined callback must accept two parameters: - * handler(resource $parser,string $prefix,string $uri) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $prefix - * The prefix is a string used to reference the namespace within an XML object. - * $uri - * Uniform Resource Identifier (URI) of namespace. - * Note: Instead of a function name, an array containing an object reference - * and a method name can also be supplied. - */ -static sxi32 VmXMLNSStartHandler(SyXMLRawStr *pUriStr, SyXMLRawStr *pPrefixStr, void *pUserData) { +/* lib.c forwards (prefix, uri) in that order. */ +static sxi32 VmXMLNSStartHandler(SyXMLRawStr *pPrefixStr, SyXMLRawStr *pUriStr, void *pUserData) { ph7_xml_engine *pEngine = (ph7_xml_engine *)pUserData; - ph7_value *pCallback, *pUri, *pPrefix; - /* Point to the target user defined callback */ - pCallback = &pEngine->aCB[PH7_XML_NS_START]; - /* Make sure the given callback is callable */ - if(!PH7_VmIsCallable(pEngine->pVm, pCallback, 0)) { - /* Not callable, return immediately*/ - return SXRET_OK; - } - /* Get a ph7_value holding the PREFIX/URI */ - pUri = VmXMLValue(pEngine, pUriStr, 0); + ph7_value *apArg[3]; + ph7_value *pPrefix, *pUri; + XmlTrackPos(pEngine, pPrefixStr); pPrefix = VmXMLValue(pEngine, pPrefixStr, 0); - if(pUri == 0 || pPrefix == 0) { - /* Out of mem, return immediately */ + pUri = VmXMLValue(pEngine, pUriStr, 0); + if(pPrefix == 0 || pUri == 0) { return SXRET_OK; } - /* Invoke the user callback */ - PH7_VmCallUserFunctionAp(pEngine->pVm, pCallback, 0, &pEngine->sParserValue, pUri, pPrefix, 0); - /* Clean-up the mess left behind */ - ph7_context_release_value(pEngine->pCtx, pUri); + apArg[0] = &pEngine->sReaderValue; + apArg[1] = pPrefix; + apArg[2] = pUri; + (void)XmlNotify(pEngine, PH7_XML_NS_START, "OnStartNamespace", apArg, 3); ph7_context_release_value(pEngine->pCtx, pPrefix); - return SXRET_OK; + ph7_context_release_value(pEngine->pCtx, pUri); + return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } -/* - * Namespace end declaration handler. - * The user defined callback must accept two parameters: - * handler(resource $parser,string $prefix) - * $parser - * The first parameter, parser, is a reference to the XML parser calling the handler. - * $prefix - * The prefix is a string used to reference the namespace within an XML object. - * Note: Instead of a function name, an array containing an object reference - * and a method name can also be supplied. - */ static sxi32 VmXMLNSEndHandler(SyXMLRawStr *pPrefixStr, void *pUserData) { ph7_xml_engine *pEngine = (ph7_xml_engine *)pUserData; - ph7_value *pCallback, *pPrefix; - /* Point to the target user defined callback */ - pCallback = &pEngine->aCB[PH7_XML_NS_END]; - /* Make sure the given callback is callable */ - if(!PH7_VmIsCallable(pEngine->pVm, pCallback, 0)) { - /* Not callable, return immediately*/ - return SXRET_OK; - } - /* Get a ph7_value holding the prefix */ + ph7_value *apArg[2]; + ph7_value *pPrefix; + XmlTrackPos(pEngine, pPrefixStr); pPrefix = VmXMLValue(pEngine, pPrefixStr, 0); if(pPrefix == 0) { - /* Out of mem, return immediately */ return SXRET_OK; } - /* Invoke the user callback */ - PH7_VmCallUserFunctionAp(pEngine->pVm, pCallback, 0, &pEngine->sParserValue, pPrefix, 0); - /* Clean-up the mess left behind */ + apArg[0] = &pEngine->sReaderValue; + apArg[1] = pPrefix; + (void)XmlNotify(pEngine, PH7_XML_NS_END, "OnEndNamespace", apArg, 2); ph7_context_release_value(pEngine->pCtx, pPrefix); - return SXRET_OK; + return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; +} +static sxi32 VmXMLDoctypeHandler(SyXMLRawStr *pRaw, void *pUserData) { + ph7_xml_engine *pEngine = (ph7_xml_engine *)pUserData; + ph7_value *apArg[2]; + ph7_value *pText; + XmlTrackPos(pEngine, pRaw); + pText = VmXMLValue(pEngine, pRaw, 0); /* raw text is not NUL-terminated */ + if(pText == 0) { + return SXRET_OK; + } + apArg[0] = &pEngine->sReaderValue; + apArg[1] = pText; + (void)XmlNotify(pEngine, PH7_XML_DOCTYPE, "OnDoctype", apArg, 2); + ph7_context_release_value(pEngine->pCtx, pText); + return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } -/* - * Error Message consumer handler. - * Each time the XML parser encounter a syntax error or any other error - * related to XML processing,the following callback is invoked by the - * underlying XML parser. - */ static sxi32 VmXMLErrorHandler(const char *zMessage, sxi32 iErrCode, SyToken *pToken, void *pUserData) { ph7_xml_engine *pEngine = (ph7_xml_engine *)pUserData; - /* Save the error code */ pEngine->iErrCode = iErrCode; - SXUNUSED(zMessage); /* cc warning */ - if(pToken) { - pEngine->nLine = pToken->nLine; + pEngine->bError = TRUE; + SyBlobReset(&pEngine->sErr); + if(zMessage) { + SyBlobAppend(&pEngine->sErr, zMessage, (sxu32)SyStrlen(zMessage)); } - /* Abort XML processing immediately */ + if(pToken) { + SyXMLRawStr sRaw; + sRaw.zString = SyStringData(&pToken->sData); + sRaw.nByte = SyStringLength(&pToken->sData); + sRaw.nLine = pToken->nLine; + XmlTrackPos(pEngine, &sRaw); + pEngine->nErrLine = pEngine->nCurLine; + pEngine->nErrCol = pEngine->nCurCol; + } + if(ph7_value_is_object(&pEngine->sHandler)) { + ph7_value *apArg[4]; + ph7_value *pMsg = ph7_context_new_scalar(pEngine->pCtx); + ph7_value *pCode = ph7_context_new_scalar(pEngine->pCtx); + ph7_value *pLine = ph7_context_new_scalar(pEngine->pCtx); + if(pMsg && pCode && pLine) { + ph7_value_string(pMsg, SyBlobData(&pEngine->sErr), (int)SyBlobLength(&pEngine->sErr)); + ph7_value_int64(pCode, pEngine->iErrCode); + ph7_value_int64(pLine, pEngine->nErrLine); + apArg[0] = &pEngine->sReaderValue; + apArg[1] = pMsg; + apArg[2] = pCode; + apArg[3] = pLine; + (void)XmlCallHandler(pEngine, "OnError", apArg, 4); + } + if(pMsg) ph7_context_release_value(pEngine->pCtx, pMsg); + if(pCode) ph7_context_release_value(pEngine->pCtx, pCode); + if(pLine) ph7_context_release_value(pEngine->pCtx, pLine); + } + /* Abort XML processing immediately. */ return SXERR_ABORT; } -/* - * int xml_parse(resource $parser,string $data[,bool $is_final = false ]) - * Parses an XML document. The handlers for the configured events are called - * as many times as necessary. - * Parameters - * $parser - * A reference to the XML parser. - * $data - * Chunk of data to parse. A document may be parsed piece-wise by calling - * xml_parse() several times with new data, as long as the is_final parameter - * is set and TRUE when the last data is parsed. - * $is_final - * NOT USED. This implementation require that all the processed input be - * entirely loaded in memory. - * Return - * Returns 1 on success or 0 on failure. - */ -static int vm_builtin_xml_parse(ph7_context *pCtx, int nArg, ph7_value **apArg) { + +/* ------------------------------------------------------------------ */ +/* XmlException support */ +/* ------------------------------------------------------------------ */ +static int XmlThrowException(ph7_context *pCtx, ph7_xml_engine *pEngine) { + ph7_vm *pVm = pCtx->pVm; + ph7_class *pClass; + ph7_class_instance *pInst = 0; + ph7_class_method *pCons; + ph7_value *pObj, *apArg[4]; + ph7_value *pMsg, *pCode, *pLine, *pCol; + sxi32 rc; + if(pVm->iPendingTransfer) { + return PH7_EXCEPTION; /* a handler exception takes precedence */ + } + pClass = PH7_VmExtractClass(pVm, "XmlException", sizeof("XmlException") - 1, FALSE); + if(pClass == 0) { + return PH7_ABORT; + } + pInst = PH7_NewClassInstance(pVm, pClass); + if(pInst == 0) { + return PH7_ABORT; + } + pCons = PH7_ClassExtractMethod(pClass, "__construct", sizeof("__construct") - 1); + pMsg = ph7_context_new_scalar(pCtx); + pCode = ph7_context_new_scalar(pCtx); + pLine = ph7_context_new_scalar(pCtx); + pCol = ph7_context_new_scalar(pCtx); + pObj = ph7_context_new_scalar(pCtx); + if(pMsg == 0 || pCode == 0 || pLine == 0 || pCol == 0 || pObj == 0) { + return PH7_ABORT; + } + ph7_value_string(pMsg, SyBlobData(&pEngine->sErr), (int)SyBlobLength(&pEngine->sErr)); + ph7_value_int64(pCode, pEngine->iErrCode); + ph7_value_int64(pLine, pEngine->nErrLine); + ph7_value_int64(pCol, pEngine->nErrCol); + apArg[0] = pMsg; + apArg[1] = pCode; + apArg[2] = pLine; + apArg[3] = pCol; + if(pCons) { + rc = PH7_VmCallClassMethod(pVm, pInst, pCons, 0, 4, apArg); + if(pInst->iRef < 1) { + pInst->iRef = 1; + } + if(rc != SXRET_OK) { + return rc; + } + } + PH7_MemObjRelease(pObj); + pObj->x.pOther = pInst; + MemObjSetType(pObj, MEMOBJ_OBJ); + (void)ph7_result_value(pCtx, pObj); + return PH7_EXCEPTION; +} + +/* ------------------------------------------------------------------ */ +/* Native class method callbacks */ +/* ------------------------------------------------------------------ */ +static int XmlHandlerNoop(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(pCtx); + SXUNUSED(nArg); + SXUNUSED(apArg); + return PH7_OK; /* void result */ +} +static int XmlExceptionConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { + static const char *const azField[] = { "xmlMessage", "xmlCode", "xmlLine", "xmlColumn" }; + ph7_value *pThis = ph7_context_this(pCtx); + sxi32 rc; + sxu32 n; + SXUNUSED(nArg); + for(n = 0 ; n < SX_ARRAYSIZE(azField) ; ++n) { + rc = ph7_context_attr_store(pCtx, pThis, 0, azField[n], apArg[n]); + if(rc != PH7_OK) { + return rc; + } + } + /* Mirror the three fields inherited Exception::getMessage()/getCode()/ + * getLine() read, so catch(Exception $e) observes the same values as the + * typed getters. apArg[2] is the line; apArg[3] is the column. */ + rc = ph7_context_attr_store(pCtx, pThis, 0, "message", apArg[0]); + if(rc != PH7_OK) { return rc; } + rc = ph7_context_attr_store(pCtx, pThis, 0, "code", apArg[1]); + if(rc != PH7_OK) { return rc; } + rc = ph7_context_attr_store(pCtx, pThis, 0, "line", apArg[2]); + if(rc != PH7_OK) { return rc; } + return PH7_OK; +} +static int XmlExceptionField(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 XmlExceptionGetDescription(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int nErr = nArg > 0 ? ph7_value_to_int(apArg[0]) : -1; + switch(nErr) { + case SXML_ERROR_NONE: return ph7_result_string(pCtx, "Not an error", -1); + case SXML_ERROR_NO_MEMORY: return ph7_result_string(pCtx, "Out of memory", -1); + case SXML_ERROR_SYNTAX: return ph7_result_string(pCtx, "Syntax error", -1); + case SXML_ERROR_INVALID_TOKEN: return ph7_result_string(pCtx, "Unexpected token", -1); + case SXML_ERROR_TAG_MISMATCH: return ph7_result_string(pCtx, "Tag mismatch", -1); + case SXML_ERROR_DUPLICATE_ATTRIBUTE: return ph7_result_string(pCtx, "Duplicate attribute", -1); + case SXML_ERROR_MISPLACED_XML_PI: return ph7_result_string(pCtx, "Misplaced processing instruction", -1); + case SXML_ERROR_INCORRECT_ENCODING: return ph7_result_string(pCtx, "Incorrect encoding", -1); + case SXML_ERROR_NO_ELEMENTS: return ph7_result_string(pCtx, "No element found", -1); + case SXML_ERROR_UNCLOSED_TOKEN: return ph7_result_string(pCtx, "Unclosed token", -1); + case SXML_ERROR_PARTIAL_CHAR: return ph7_result_string(pCtx, "Partial character", -1); + case SXML_ERROR_JUNK_AFTER_DOC_ELEMENT: return ph7_result_string(pCtx, "Junk after document element", -1); + case SXML_ERROR_PARAM_ENTITY_REF: return ph7_result_string(pCtx, "Parameter entity reference", -1); + case SXML_ERROR_UNDEFINED_ENTITY: return ph7_result_string(pCtx, "Undefined entity", -1); + case SXML_ERROR_RECURSIVE_ENTITY_REF: return ph7_result_string(pCtx, "Recursive entity reference", -1); + case SXML_ERROR_ASYNC_ENTITY: return ph7_result_string(pCtx, "Asynchronous entity", -1); + case SXML_ERROR_BAD_CHAR_REF: return ph7_result_string(pCtx, "Bad character reference", -1); + case SXML_ERROR_BINARY_ENTITY_REF: return ph7_result_string(pCtx, "Binary entity reference", -1); + case SXML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: return ph7_result_string(pCtx, "External entity reference in attribute", -1); + case SXML_ERROR_UNKNOWN_ENCODING: return ph7_result_string(pCtx, "Unknown encoding", -1); + case SXML_ERROR_UNCLOSED_CDATA_SECTION: return ph7_result_string(pCtx, "Unclosed CDATA section", -1); + case SXML_ERROR_EXTERNAL_ENTITY_HANDLING: return ph7_result_string(pCtx, "External entity handling", -1); + default: return ph7_result_string(pCtx, "Unknown error code", -1); + } +} + +/* Locate the engine payload of an XmlReader receiver. */ +static ph7_xml_engine *XmlReaderEngine(ph7_context *pCtx) { + ph7_value *pRes = ph7_context_new_scalar(pCtx); + ph7_xml_engine *pEngine = 0; + if(pRes == 0) { + return 0; + } + if(ph7_context_attr_value(pCtx, ph7_context_this(pCtx), 0, "resource", pRes) == PH7_OK && + ph7_value_is_resource(pRes)) { + pEngine = (ph7_xml_engine *)ph7_value_to_resource(pRes); + if(IS_INVALID_XML_ENGINE(pEngine)) { + pEngine = 0; + } + } + ph7_context_release_value(pCtx, pRes); + return pEngine; +} +static int XmlReaderCreate(ph7_context *pCtx, int process_ns, int ns_sep) { + ph7_xml_engine *pEngine = VmCreateXMLEngine(pCtx, process_ns, ns_sep); + ph7_value *pRes; + if(pEngine == 0) { + PH7_VmMemoryError(pCtx->pVm); + return PH7_ABORT; + } + pRes = ph7_context_new_scalar(pCtx); + if(pRes == 0) { + VmReleaseXMLEngine(pEngine); + return PH7_ABORT; + } + ph7_value_resource(pRes, pEngine); + { + sxi32 rc = ph7_context_attr_store(pCtx, ph7_context_this(pCtx), 0, "resource", pRes); + if(rc != PH7_OK) { + ph7_value_resource(pRes, 0); + VmReleaseXMLEngine(pEngine); + ph7_context_release_value(pCtx, pRes); + return rc; + } + ph7_context_release_value(pCtx, pRes); + return PH7_OK; + } +} +static int XmlReaderConstruct0(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); + return XmlReaderCreate(pCtx, FALSE, ':'); +} +static int XmlReaderConstruct2(ph7_context *pCtx, int nArg, ph7_value **apArg) { + /* $separator is accepted for API compatibility but reserved/ignored: the + * typed getters forward the QName components verbatim instead of gluing + * URI + separator + local name. */ + int ns_sep = ':'; + if(nArg > 1 && ph7_value_is_string(apArg[1])) { + const char *zSep = ph7_value_to_string(apArg[1], 0); + if(zSep && zSep[0] != 0) { + ns_sep = zSep[0]; + } + } + return XmlReaderCreate(pCtx, ph7_value_to_bool(apArg[0]) ? TRUE : FALSE, ns_sep); +} +static int XmlReaderCloseCtx(ph7_context *pCtx) { + ph7_value *pRes = ph7_context_new_scalar(pCtx); + ph7_xml_engine *pEngine; + if(pRes == 0) { + return PH7_ABORT; + } + if(ph7_context_attr_value(pCtx, ph7_context_this(pCtx), 0, "resource", pRes) == PH7_OK && + ph7_value_is_resource(pRes)) { + pEngine = (ph7_xml_engine *)ph7_value_to_resource(pRes); + if(!IS_INVALID_XML_ENGINE(pEngine)) { + VmReleaseXMLEngine(pEngine); + ph7_value_resource(pRes, 0); /* invalidate: future access is harmless */ + (void)ph7_context_attr_store(pCtx, ph7_context_this(pCtx), 0, "resource", pRes); + } + } + ph7_context_release_value(pCtx, pRes); + return PH7_OK; +} +static int XmlReaderClose(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); + return XmlReaderCloseCtx(pCtx); +} +static int XmlReaderDestruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); + return XmlReaderCloseCtx(pCtx); +} +static int XmlReaderParse(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_xml_engine *pEngine; SyXMLParser *pParser; const char *zData; int nByte; - if(nArg < 2 || !ph7_value_is_resource(apArg[0]) || !ph7_value_is_string(apArg[1])) { - /* Missing/Ivalid arguments, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; + SXUNUSED(nArg); /* isFinal stays ignored, as in the underlying engine */ + if(nArg < 1 || !ph7_value_is_string(apArg[0])) { + return PH7_ABORT; } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; + pEngine = XmlReaderEngine(pCtx); + if(pEngine == 0) { + return PH7_ABORT; } if(pEngine->iNest > 0) { - /* This can happen when the user callback call xml_parse() again - * in it's body which is forbidden. - */ PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, - "Recursive call to %s, PH7 is returning false", - ph7_function_name(pCtx) - ); - /* Return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; + "Recursive call to %s, PH7 is returning false", ph7_function_name(pCtx)); + return PH7_ABORT; } pEngine->pCtx = pCtx; - /* Point to the underlying XML parser */ - pParser = &pEngine->sParser; - /* Register elements handler */ - SyXMLParserSetEventHandler(pParser, pEngine, - VmXMLStartElementHandler, - VmXMLTextHandler, - VmXMLErrorHandler, - 0, - VmXMLEndElementHandler, - VmXMLPIHandler, - 0, - 0, - VmXMLNSStartHandler, - VmXMLNSEndHandler - ); + /* Reset all transient state, including after a previous abort. */ pEngine->iErrCode = SXML_ERROR_NONE; - /* Extract the raw XML input */ - zData = ph7_value_to_string(apArg[1], &nByte); - /* Start the parse process */ + pEngine->bError = FALSE; + pEngine->bAbort = FALSE; + pEngine->nErrLine = 0; + pEngine->nErrCol = 0; + pEngine->nDepth = 0; + pEngine->bEmptyElement = FALSE; + pEngine->nCurLine = 0; + pEngine->iCurByte = 0; + pEngine->nCurCol = 0; + SyBlobReset(&pEngine->sErr); + PH7_MemObjRelease(&pEngine->sReaderValue); + PH7_MemObjInit(pCtx->pVm, &pEngine->sReaderValue); + PH7_MemObjStore(ph7_context_this(pCtx), &pEngine->sReaderValue); + pParser = &pEngine->sParser; + /* SyLexTokenizeInput() appends to sToken and ProcessXML() restarts its + * cursor at zero once exhausted. Drop tokens from any previous Parse() so + * a reused reader does not replay stale events (whose sData pointed into + * the previous, possibly already released, input buffer). SyToken only + * borrows the input buffer, so resetting the set owns/frees nothing. */ + SySetReset(&pParser->sToken); + SyXMLParserSetEventHandler(pParser, pEngine, + VmXMLStartElementHandler, VmXMLTextHandler, VmXMLErrorHandler, 0, + VmXMLEndElementHandler, VmXMLPIHandler, 0, VmXMLDoctypeHandler, + VmXMLNSStartHandler, VmXMLNSEndHandler); + zData = ph7_value_to_string(apArg[0], &nByte); pEngine->iNest++; SyXMLProcess(pParser, zData, (sxu32)nByte); pEngine->iNest--; - /* Return the parse result */ - ph7_result_int(pCtx, pEngine->iErrCode == SXML_ERROR_NONE ? 1 : 0); - return PH7_OK; + PH7_MemObjRelease(&pEngine->sReaderValue); + PH7_MemObjInit(pCtx->pVm, &pEngine->sReaderValue); + if(pCtx->pVm->iPendingTransfer) { + return PH7_EXCEPTION; /* exception from a user handler */ + } + if(pEngine->bError) { + return XmlThrowException(pCtx, pEngine); + } + if(pEngine->bAbort) { + return PH7_ABORT; /* e.g. exit() from OnDoctype rejects the document */ + } + return PH7_OK; /* void */ } -/* - * bool xml_parser_set_option(resource $parser,int $option,mixed $value) - * Sets an option in an XML parser. - * Parameters - * $parser - * A reference to the XML parser to set an option in. - * $option - * Which option to set. See below. - * The following options are available: - * XML_OPTION_CASE_FOLDING integer Controls whether case-folding is enabled for this XML parser. - * XML_OPTION_SKIP_TAGSTART integer Specify how many characters should be skipped in the beginning of a tag name. - * XML_OPTION_SKIP_WHITE integer Whether to skip values consisting of whitespace characters. - * XML_OPTION_TARGET_ENCODING string Sets which target encoding to use in this XML parser. - * $value - * The option's new value. - * Return - * Returns 1 on success or 0 on failure. - * Note: - * Well,none of these options have meaning under the built-in XML parser so a call to this - * function is a no-op. - */ -static int vm_builtin_xml_parser_set_option(ph7_context *pCtx, int nArg, ph7_value **apArg) { +static int XmlReaderCurrentLine(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + SXUNUSED(nArg); + SXUNUSED(apArg); + return pEngine ? ph7_result_int64(pCtx, pEngine->nCurLine) : PH7_ABORT; +} +static int XmlReaderCurrentByteIndex(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + SXUNUSED(nArg); + SXUNUSED(apArg); + return pEngine ? ph7_result_int64(pCtx, pEngine->iCurByte) : PH7_ABORT; +} +static int XmlReaderCurrentColumn(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + SXUNUSED(nArg); + SXUNUSED(apArg); + return pEngine ? ph7_result_int64(pCtx, pEngine->nCurCol) : PH7_ABORT; +} +static int XmlReaderDepth(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + SXUNUSED(nArg); + SXUNUSED(apArg); + return pEngine ? ph7_result_int64(pCtx, pEngine->nDepth) : PH7_ABORT; +} +static int XmlReaderIsEmptyElement(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + SXUNUSED(nArg); + SXUNUSED(apArg); + return pEngine ? ph7_result_bool(pCtx, pEngine->bEmptyElement) : PH7_ABORT; +} +static int XmlReaderStringField(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_xml_engine *pEngine; - if(nArg < 2 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; + SXUNUSED(nArg); + SXUNUSED(apArg); + pEngine = XmlReaderEngine(pCtx); + if(pEngine == 0) { + return PH7_ABORT; } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; + return ph7_result_value(pCtx, + (ph7_value *)((char *)pEngine + (size_t)(uintptr_t)ph7_context_user_data(pCtx))); +} +static int XmlReaderGetAttributeCount(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + SXUNUSED(nArg); + SXUNUSED(apArg); + if(pEngine == 0) { + return PH7_ABORT; } - /* Always return FALSE */ - ph7_result_bool(pCtx, 0); + return ph7_result_int64(pCtx, ph7_value_is_array(&pEngine->sAttrs) ? ph7_array_count(&pEngine->sAttrs) : 0); +} +struct XmlAttrWalk { + int nTarget; + int nCur; + ph7_value *pName; + ph7_value *pValue; +}; +static int XmlAttrWalker(ph7_value *pKey, ph7_value *pValue, void *pUserData) { + struct XmlAttrWalk *pWalk = (struct XmlAttrWalk *)pUserData; + if(pWalk->nCur == pWalk->nTarget) { + PH7_MemObjStore(pKey, pWalk->pName); + PH7_MemObjStore(pValue, pWalk->pValue); + return 1; /* stop */ + } + ++pWalk->nCur; + return 0; +} +static int XmlReaderAttributeAt(ph7_context *pCtx, int nArg, ph7_value **apArg, int wantName) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_value *pName, *pValue, *pOut; + struct XmlAttrWalk sWalk; + SXUNUSED(nArg); + if(pEngine == 0) { + return PH7_ABORT; + } + pName = ph7_context_new_scalar(pCtx); + pValue = ph7_context_new_scalar(pCtx); + pOut = wantName ? pName : pValue; + if(pName == 0 || pValue == 0) { + return PH7_ABORT; + } + sWalk.nTarget = ph7_value_to_int(apArg[0]); + sWalk.nCur = 0; + sWalk.pName = pName; + sWalk.pValue = pValue; + if(ph7_value_is_array(&pEngine->sAttrs) && sWalk.nTarget >= 0) { + (void)ph7_array_walk(&pEngine->sAttrs, XmlAttrWalker, &sWalk); + } + return ph7_result_value(pCtx, pOut); +} +static int XmlReaderGetAttributeName(ph7_context *pCtx, int nArg, ph7_value **apArg) { + return XmlReaderAttributeAt(pCtx, nArg, apArg, TRUE); +} +static int XmlReaderGetAttributeValue(ph7_context *pCtx, int nArg, ph7_value **apArg) { + return XmlReaderAttributeAt(pCtx, nArg, apArg, FALSE); +} +static int XmlReaderGetAttribute(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_value *pValue; + int nLen; + const char *zName; + SXUNUSED(nArg); + if(pEngine == 0) { + return PH7_ABORT; + } + zName = ph7_value_to_string(apArg[0], &nLen); + if(ph7_context_status(pCtx) != PH7_OK) { + return ph7_context_status(pCtx); + } + pValue = ph7_value_is_array(&pEngine->sAttrs) ? ph7_array_fetch(&pEngine->sAttrs, zName, nLen) : 0; + return pValue ? ph7_result_value(pCtx, pValue) : ph7_result_string(pCtx, "", 0); +} +static int XmlReaderHasAttribute(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_value *pValue; + int nLen; + const char *zName; + SXUNUSED(nArg); + if(pEngine == 0) { + return PH7_ABORT; + } + zName = ph7_value_to_string(apArg[0], &nLen); + if(ph7_context_status(pCtx) != PH7_OK) { + return ph7_context_status(pCtx); + } + pValue = ph7_value_is_array(&pEngine->sAttrs) ? ph7_array_fetch(&pEngine->sAttrs, zName, nLen) : 0; + return ph7_result_bool(pCtx, pValue != 0); +} +static int XmlReaderLookupNamespace(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + SyHashEntry *pEntry; + const char *zPrefix; + int nLen; + SXUNUSED(nArg); + if(pEngine == 0) { + return PH7_ABORT; + } + zPrefix = ph7_value_to_string(apArg[0], &nLen); + if(ph7_context_status(pCtx) != PH7_OK) { + return ph7_context_status(pCtx); + } + if(nLen == 0) { + zPrefix = "Default"; + nLen = sizeof("Default") - 1; + } + /* Visibility is limited to the current element: lib.c removes the hash + * entry in XMLnsUnlink() when the element closes. */ + pEntry = SyHashGet(&pEngine->sParser.hns, zPrefix, (sxu32)nLen); + if(pEntry && pEntry->pUserData) { + SyXMLRawStr *pUri = (SyXMLRawStr *)pEntry->pUserData; + return ph7_result_string(pCtx, pUri->zString, (int)pUri->nByte); + } + return ph7_result_string(pCtx, "", 0); +} +static int XmlReaderSetHandler(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + SXUNUSED(nArg); + if(pEngine == 0) { + return PH7_ABORT; + } + PH7_MemObjRelease(&pEngine->sHandler); + PH7_MemObjInit(pCtx->pVm, &pEngine->sHandler); + PH7_MemObjStore(apArg[0], &pEngine->sHandler); return PH7_OK; } -/* - * mixed xml_parser_get_option(resource $parser,int $option) - * Get options from an XML parser. - * Parameters - * $parser - * A reference to the XML parser to set an option in. - * $option - * Which option to fetch. - * Return - * This function returns FALSE if parser does not refer to a valid parser - * or if option isn't valid.Else the option's value is returned. - */ -static int vm_builtin_xml_parser_get_option(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine; - int nOp; - if(nArg < 2 || !ph7_value_is_resource(apArg[0])) { - /* Missing/Ivalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the XML engine */ - pEngine = (ph7_xml_engine *)ph7_value_to_resource(apArg[0]); - if(IS_INVALID_XML_ENGINE(pEngine)) { - /* Corrupt engine, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Extract the option */ - nOp = ph7_value_to_int(apArg[1]); - switch(nOp) { - case SXML_OPTION_SKIP_TAGSTART: - case SXML_OPTION_SKIP_WHITE: - case SXML_OPTION_CASE_FOLDING: - ph7_result_int(pCtx, 0); - break; - case SXML_OPTION_TARGET_ENCODING: - ph7_result_string(pCtx, "UTF-8", (int)sizeof("UTF-8") - 1); - break; - default: - /* Unknown option, return FALSE*/ - ph7_result_bool(pCtx, 0); - break; +static int XmlReaderSetCallback(ph7_context *pCtx, int nArg, ph7_value **apArg) { + int nSlot = (int)(long)ph7_context_user_data(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + SXUNUSED(nArg); + if(pEngine == 0 || nSlot < 0 || nSlot >= XML_TOTAL_HANDLER) { + return PH7_ABORT; } + PH7_MemObjRelease(&pEngine->aCB[nSlot]); + PH7_MemObjInit(pCtx->pVm, &pEngine->aCB[nSlot]); + PH7_MemObjStore(apArg[0], &pEngine->aCB[nSlot]); return PH7_OK; } -/* - * string xml_error_string(int $code) - * Gets the XML parser error string associated with the given code. - * Parameters - * $code - * An error code from xml_get_error_code(). - * Return - * Returns a string with a textual description of the error - * code, or FALSE if no description was found. - */ -static int vm_builtin_xml_error_string(ph7_context *pCtx, int nArg, ph7_value **apArg) { - int nErr = -1; - if(nArg > 0) { - nErr = ph7_value_to_int(apArg[0]); +static int XmlReaderClearHandler(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + SXUNUSED(nArg); SXUNUSED(apArg); + if(pEngine == 0) return PH7_ABORT; + PH7_MemObjRelease(&pEngine->sHandler); + PH7_MemObjInit(pCtx->pVm, &pEngine->sHandler); + return PH7_OK; /* void */ +} +static int XmlReaderClearCallbacks(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + sxu32 n; + SXUNUSED(nArg); SXUNUSED(apArg); + if(pEngine == 0) return PH7_ABORT; + for(n = 0 ; n < SX_ARRAYSIZE(pEngine->aCB) ; ++n) { + PH7_MemObjRelease(&pEngine->aCB[n]); + PH7_MemObjInit(pCtx->pVm, &pEngine->aCB[n]); } - switch(nErr) { - case SXML_ERROR_DUPLICATE_ATTRIBUTE: - ph7_result_string(pCtx, "Duplicate attribute", -1/*Compute length automatically*/); - break; - case SXML_ERROR_INCORRECT_ENCODING: - ph7_result_string(pCtx, "Incorrect encoding", -1); - break; - case SXML_ERROR_INVALID_TOKEN: - ph7_result_string(pCtx, "Unexpected token", -1); - break; - case SXML_ERROR_MISPLACED_XML_PI: - ph7_result_string(pCtx, "Misplaced processing instruction", -1); - break; - case SXML_ERROR_NO_MEMORY: - ph7_result_string(pCtx, "Out of memory", -1); - break; - case SXML_ERROR_NONE: - ph7_result_string(pCtx, "Not an error", -1); - break; - case SXML_ERROR_TAG_MISMATCH: - ph7_result_string(pCtx, "Tag mismatch", -1); - break; - case -1: - ph7_result_string(pCtx, "Unknown error code", -1); - break; - default: - ph7_result_string(pCtx, "Syntax error", -1); - break; + return PH7_OK; /* void */ +} + +/* ------------------------------------------------------------------ */ +/* Native class registration */ +/* ------------------------------------------------------------------ */ +#define XTY(T) { PH7_TYPE_##T, 0, 0 } +#define XNM(N) { PH7_TYPE_NAMED, N, 0 } +#define XP(N,T) { N, XTY(T), 0, 0, 0, 0 } + +/* The pValue pointers are filled in per VM registration and cleared again + * afterwards: these tables are static and must never retain a stale value. */ +static ph7_constant_def aExceptionConst[] = { + { "ERROR_NONE", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_NO_MEMORY", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_SYNTAX", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_NO_ELEMENTS", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_INVALID_TOKEN", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_UNCLOSED_TOKEN", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_PARTIAL_CHAR", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_TAG_MISMATCH", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_DUPLICATE_ATTRIBUTE", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_JUNK_AFTER_DOC_ELEMENT", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_PARAM_ENTITY_REF", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_UNDEFINED_ENTITY", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_RECURSIVE_ENTITY_REF", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_ASYNC_ENTITY", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_BAD_CHAR_REF", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_BINARY_ENTITY_REF", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_MISPLACED_XML_PI", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_UNKNOWN_ENCODING", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_INCORRECT_ENCODING", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_UNCLOSED_CDATA_SECTION", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_EXTERNAL_ENTITY_HANDLING", 0, PH7_MEMBER_PUBLIC, 0, 0 } +}; +/* Same order as aExceptionConst and enum xml_err_code. */ +static const int aExceptionConstValue[] = { + SXML_ERROR_NONE, SXML_ERROR_NO_MEMORY, SXML_ERROR_SYNTAX, SXML_ERROR_NO_ELEMENTS, + SXML_ERROR_INVALID_TOKEN, SXML_ERROR_UNCLOSED_TOKEN, SXML_ERROR_PARTIAL_CHAR, + SXML_ERROR_TAG_MISMATCH, SXML_ERROR_DUPLICATE_ATTRIBUTE, + SXML_ERROR_JUNK_AFTER_DOC_ELEMENT, SXML_ERROR_PARAM_ENTITY_REF, + SXML_ERROR_UNDEFINED_ENTITY, SXML_ERROR_RECURSIVE_ENTITY_REF, SXML_ERROR_ASYNC_ENTITY, + SXML_ERROR_BAD_CHAR_REF, SXML_ERROR_BINARY_ENTITY_REF, + SXML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, SXML_ERROR_MISPLACED_XML_PI, + SXML_ERROR_UNKNOWN_ENCODING, SXML_ERROR_INCORRECT_ENCODING, + SXML_ERROR_UNCLOSED_CDATA_SECTION, SXML_ERROR_EXTERNAL_ENTITY_HANDLING +}; + +static sxi32 XmlRegisterClasses(ph7_vm *pVm) { + static const ph7_param_def aReaderInt[] = { XP("index", INT) }; + static const ph7_param_def aReaderString[] = { XP("name", STRING) }; + static const ph7_param_def aReaderPrefix[] = { XP("prefix", STRING) }; + static ph7_param_def aCtor2[] = { + XP("namespaces", BOOL), { "separator", XTY(STRING), 0, 0, 0, 0 } + }; + static ph7_param_def aParse[] = { + XP("data", STRING), { "isFinal", XTY(BOOL), 0, 0, 0, 0 } + }; + static const ph7_param_def aSetHandler[] = { { "handler", XNM("IXmlHandler"), 0, 0, 0, 0 } }; + static const ph7_param_def aCallback[] = { XP("fn", CALLBACK) }; + static const ph7_param_def aExcCtor[] = { + XP("message", STRING), XP("code", INT), XP("line", INT), XP("column", INT) + }; + static const ph7_param_def aExcDesc[] = { XP("code", INT) }; + /* IXmlHandler signatures */ + static const ph7_param_def aOnStart[] = { + { "reader", XNM("XmlReader"), 0, 0, 0, 0 }, + XP("name", STRING), { "attributes", { PH7_TYPE_STRING, 0, 1 }, 0, 0, 0, 0 } + }; + static const ph7_param_def aOnEnd[] = { + { "reader", XNM("XmlReader"), 0, 0, 0, 0 }, XP("name", STRING) + }; + static const ph7_param_def aOnText[] = { + { "reader", XNM("XmlReader"), 0, 0, 0, 0 }, XP("text", STRING) + }; + static const ph7_param_def aOnPI[] = { + { "reader", XNM("XmlReader"), 0, 0, 0, 0 }, + XP("target", STRING), XP("data", STRING) + }; + static const ph7_param_def aOnNSStart[] = { + { "reader", XNM("XmlReader"), 0, 0, 0, 0 }, + XP("prefix", STRING), XP("uri", STRING) + }; + static const ph7_param_def aOnNSEnd[] = { + { "reader", XNM("XmlReader"), 0, 0, 0, 0 }, XP("prefix", STRING) + }; + static const ph7_param_def aOnDoctype[] = { + { "reader", XNM("XmlReader"), 0, 0, 0, 0 }, XP("raw", STRING) + }; + static const ph7_param_def aOnError[] = { + { "reader", XNM("XmlReader"), 0, 0, 0, 0 }, + XP("message", STRING), XP("code", INT), XP("line", INT) + }; + /* Interface: public nonstatic signatures, no callbacks. */ + static const ph7_method_def aIfaceMethod[] = { + { "OnStartElement", XTY(VOID), aOnStart, 3, 0, 0, 0 }, + { "OnEndElement", XTY(VOID), aOnEnd, 2, 0, 0, 0 }, + { "OnText", XTY(VOID), aOnText, 2, 0, 0, 0 }, + { "OnProcessingInstruction", XTY(VOID), aOnPI, 3, 0, 0, 0 }, + { "OnStartNamespace", XTY(VOID), aOnNSStart, 3, 0, 0, 0 }, + { "OnEndNamespace", XTY(VOID), aOnNSEnd, 2, 0, 0, 0 }, + { "OnDoctype", XTY(VOID), aOnDoctype, 2, 0, 0, 0 }, + { "OnError", XTY(VOID), aOnError, 4, 0, 0, 0 } + }; + /* XmlHandler: concrete public non-final methods with empty bodies. */ + static const ph7_method_def aHandlerMethod[] = { + { "OnStartElement", XTY(VOID), aOnStart, 3, XmlHandlerNoop, 0, PH7_MEMBER_PUBLIC }, + { "OnEndElement", XTY(VOID), aOnEnd, 2, XmlHandlerNoop, 0, PH7_MEMBER_PUBLIC }, + { "OnText", XTY(VOID), aOnText, 2, XmlHandlerNoop, 0, PH7_MEMBER_PUBLIC }, + { "OnProcessingInstruction", XTY(VOID), aOnPI, 3, XmlHandlerNoop, 0, PH7_MEMBER_PUBLIC }, + { "OnStartNamespace", XTY(VOID), aOnNSStart, 3, XmlHandlerNoop, 0, PH7_MEMBER_PUBLIC }, + { "OnEndNamespace", XTY(VOID), aOnNSEnd, 2, XmlHandlerNoop, 0, PH7_MEMBER_PUBLIC }, + { "OnDoctype", XTY(VOID), aOnDoctype, 2, XmlHandlerNoop, 0, PH7_MEMBER_PUBLIC }, + { "OnError", XTY(VOID), aOnError, 4, XmlHandlerNoop, 0, PH7_MEMBER_PUBLIC } + }; + static const char *const aHandlerIf[] = { "IXmlHandler" }; + static const ph7_field_def aExcField[] = { + { "xmlMessage", XTY(STRING), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "xmlCode", XTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "xmlLine", XTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "xmlColumn", XTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 } + }; + static const char *const aExcBase[] = { "Exception" }; + static const ph7_method_def aExcMethod[] = { + { "__construct", XTY(VOID), aExcCtor, 4, XmlExceptionConstruct, 0, 0 }, + { "GetMessage", XTY(STRING), 0, 0, XmlExceptionField, (void *)"xmlMessage", PH7_MEMBER_PUBLIC }, + { "GetCode", XTY(INT), 0, 0, XmlExceptionField, (void *)"xmlCode", PH7_MEMBER_PUBLIC }, + { "GetLine", XTY(INT), 0, 0, XmlExceptionField, (void *)"xmlLine", PH7_MEMBER_PUBLIC }, + { "GetColumn", XTY(INT), 0, 0, XmlExceptionField, (void *)"xmlColumn", PH7_MEMBER_PUBLIC }, + { "GetDescription", XTY(STRING), aExcDesc, 1, XmlExceptionGetDescription, 0, + PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC } + }; + /* XmlReader methods */ + static const ph7_method_def aReaderMethod[] = { + { "__construct", XTY(VOID), 0, 0, XmlReaderConstruct0, 0, 0 }, + { "__construct", XTY(VOID), aCtor2, 2, XmlReaderConstruct2, 0, 0 }, + { "Parse", XTY(VOID), aParse, 2, XmlReaderParse, 0, PH7_MEMBER_PUBLIC }, + { "Close", XTY(VOID), 0, 0, XmlReaderClose, 0, PH7_MEMBER_PUBLIC }, + { "__destruct", XTY(VOID), 0, 0, XmlReaderDestruct, 0, 0 }, + { "CurrentLine", XTY(INT), 0, 0, XmlReaderCurrentLine, 0, PH7_MEMBER_PUBLIC }, + { "CurrentByteIndex", XTY(INT), 0, 0, XmlReaderCurrentByteIndex, 0, PH7_MEMBER_PUBLIC }, + { "CurrentColumn", XTY(INT), 0, 0, XmlReaderCurrentColumn, 0, PH7_MEMBER_PUBLIC }, + { "GetAttributeCount", XTY(INT), 0, 0, XmlReaderGetAttributeCount, 0, PH7_MEMBER_PUBLIC }, + { "Depth", XTY(INT), 0, 0, XmlReaderDepth, 0, PH7_MEMBER_PUBLIC }, + { "IsEmptyElement", XTY(BOOL), 0, 0, XmlReaderIsEmptyElement, 0, PH7_MEMBER_PUBLIC }, + { "LocalName", XTY(STRING), 0, 0, XmlReaderStringField, (void *)(uintptr_t)offsetof(ph7_xml_engine, sLocalName), PH7_MEMBER_PUBLIC }, + { "NamespaceUri", XTY(STRING), 0, 0, XmlReaderStringField, (void *)(uintptr_t)offsetof(ph7_xml_engine, sNsUri), PH7_MEMBER_PUBLIC }, + { "Prefix", XTY(STRING), 0, 0, XmlReaderStringField, (void *)(uintptr_t)offsetof(ph7_xml_engine, sPrefix), PH7_MEMBER_PUBLIC }, + { "GetAttributeName", XTY(STRING), aReaderInt, 1, XmlReaderGetAttributeName, 0, PH7_MEMBER_PUBLIC }, + { "GetAttributeValue", XTY(STRING), aReaderInt, 1, XmlReaderGetAttributeValue, 0, PH7_MEMBER_PUBLIC }, + { "GetAttribute", XTY(STRING), aReaderString, 1, XmlReaderGetAttribute, 0, PH7_MEMBER_PUBLIC }, + { "HasAttribute", XTY(BOOL), aReaderString, 1, XmlReaderHasAttribute, 0, PH7_MEMBER_PUBLIC }, + { "LookupNamespace", XTY(STRING), aReaderPrefix, 1, XmlReaderLookupNamespace, 0, PH7_MEMBER_PUBLIC }, + { "SetHandler", XTY(VOID), aSetHandler, 1, XmlReaderSetHandler, 0, PH7_MEMBER_PUBLIC }, + { "ClearHandler", XTY(VOID), 0, 0, XmlReaderClearHandler, 0, PH7_MEMBER_PUBLIC }, + { "ClearCallbacks", XTY(VOID), 0, 0, XmlReaderClearCallbacks, 0, PH7_MEMBER_PUBLIC }, + { "OnStartElement", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_START_TAG, PH7_MEMBER_PUBLIC }, + { "OnEndElement", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_END_TAG, PH7_MEMBER_PUBLIC }, + { "OnText", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_CDATA, PH7_MEMBER_PUBLIC }, + { "OnProcessingInstruction", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_PI, PH7_MEMBER_PUBLIC }, + { "OnStartNamespace", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_NS_START, PH7_MEMBER_PUBLIC }, + { "OnEndNamespace", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_NS_END, PH7_MEMBER_PUBLIC }, + { "OnDoctype", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_DOCTYPE, PH7_MEMBER_PUBLIC } + }; + static const ph7_field_def aReaderField[] = { + { "resource", XTY(RESOURCE), 0, PH7_MEMBER_PRIVATE, 0, 0 } + }; + ph7_class_def sIface = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, + "IXmlHandler", 0, 0, 0, 0, aIfaceMethod, SX_ARRAYSIZE(aIfaceMethod), + PH7_DECL_INTERFACE, 0, 0, 0, 0, 0, 0 }; + ph7_class_def sHandler = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, + "XmlHandler", 0, 0, 0, 0, aHandlerMethod, SX_ARRAYSIZE(aHandlerMethod), + 0, 0, 0, aHandlerIf, 1, 0, 0 }; + ph7_class_def sExc = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, + "XmlException", aExcField, SX_ARRAYSIZE(aExcField), + aExceptionConst, SX_ARRAYSIZE(aExceptionConst), + aExcMethod, SX_ARRAYSIZE(aExcMethod), 0, aExcBase, 1, 0, 0, 0, 0 }; + ph7_class_def sReader = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, + "XmlReader", aReaderField, SX_ARRAYSIZE(aReaderField), 0, 0, + aReaderMethod, SX_ARRAYSIZE(aReaderMethod), 0, 0, 0, 0, 0, 0, 0 }; + ph7_value *pSep = ph7_new_scalar(pVm); + ph7_value *pTrue = ph7_new_scalar(pVm); + ph7_value *apErrVal[SX_ARRAYSIZE(aExceptionConst)]; + sxu32 n; + sxi32 rc; + if(pSep == 0 || pTrue == 0) { + if(pSep) ph7_release_value(pVm, pSep); + if(pTrue) ph7_release_value(pVm, pTrue); + return PH7_ABORT; } - return PH7_OK; + for(n = 0 ; n < SX_ARRAYSIZE(aExceptionConst) ; ++n) { + apErrVal[n] = ph7_new_scalar(pVm); + if(apErrVal[n] == 0) { + while(n > 0) { + --n; + ph7_release_value(pVm, apErrVal[n]); + aExceptionConst[n].pValue = 0; + } + ph7_release_value(pVm, pSep); + ph7_release_value(pVm, pTrue); + return PH7_ABORT; + } + ph7_value_int(apErrVal[n], aExceptionConstValue[n]); + aExceptionConst[n].pValue = apErrVal[n]; + } + ph7_value_string(pSep, ":", 1); + ph7_value_bool(pTrue, 1); + aCtor2[1].pDefault = pSep; + aParse[1].pDefault = pTrue; + rc = ph7_create_class(pVm, &sIface); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sHandler); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sExc); + if(rc == PH7_OK) rc = ph7_create_class(pVm, &sReader); + for(n = 0 ; n < SX_ARRAYSIZE(aExceptionConst) ; ++n) { + ph7_release_value(pVm, apErrVal[n]); + aExceptionConst[n].pValue = 0; /* static table: no dangling pointer across VMs */ + } + aCtor2[1].pDefault = 0; + aParse[1].pDefault = 0; + ph7_release_value(pVm, pSep); + ph7_release_value(pVm, pTrue); + return rc; } PH7_PRIVATE sxi32 initializeModule(ph7_vm *pVm, ph7_real *ver, SyString *desc) { - sxi32 rc; - sxu32 n; desc->zString = MODULE_DESC; *ver = MODULE_VER; - for(n = 0; n < SX_ARRAYSIZE(xmlConstList); ++n) { - rc = ph7_create_constant(&(*pVm), xmlConstList[n].zName, xmlConstList[n].xExpand, &(*pVm)); - if(rc != SXRET_OK) { - return rc; - } - } - for(n = 0; n < SX_ARRAYSIZE(xmlFuncList); ++n) { - rc = ph7_create_function(&(*pVm), xmlFuncList[n].zName, xmlFuncList[n].xFunc, &(*pVm)); - if(rc != SXRET_OK) { - return rc; - } - } - return SXRET_OK; -} \ No newline at end of file + return XmlRegisterClasses(pVm); +} diff --git a/modules/xml/xml.h b/modules/xml/xml.h index ed5a27d..ce8a2ed 100644 --- a/modules/xml/xml.h +++ b/modules/xml/xml.h @@ -2,7 +2,7 @@ * @PROJECT AerScript Interpreter * @COPYRIGHT See COPYING in the top level directory * @FILE modules/xml/xml.h - * @DESCRIPTION XML parser module for AerScript Interpreter + * @DESCRIPTION Typed XML SAX module for AerScript Interpreter * @DEVELOPERS Symisc Systems * Rafal Kupiec */ @@ -16,145 +16,61 @@ #define MODULE_DESC "XML Module" #define MODULE_VER 1.0 -#define XML_TOTAL_HANDLER (PH7_XML_NS_END + 1) +#define XML_TOTAL_HANDLER (PH7_XML_DOCTYPE + 1) #define XML_ENGINE_MAGIC 0x851EFC52 #define IS_INVALID_XML_ENGINE(XML) (XML == 0 || (XML)->nMagic != XML_ENGINE_MAGIC) enum ph7_xml_handler_id { - PH7_XML_START_TAG = 0, /* Start element handlers ID */ - PH7_XML_END_TAG, /* End element handler ID*/ - PH7_XML_CDATA, /* Character data handler ID*/ - PH7_XML_PI, /* Processing instruction (PI) handler ID*/ - PH7_XML_DEF, /* Default handler ID */ - PH7_XML_UNPED, /* Unparsed entity declaration handler */ - PH7_XML_ND, /* Notation declaration handler ID*/ - PH7_XML_EER, /* External entity reference handler */ - PH7_XML_NS_START, /* Start namespace declaration handler */ - PH7_XML_NS_END /* End namespace declaration handler */ + PH7_XML_START_TAG = 0, /* Start element */ + PH7_XML_END_TAG, /* End element */ + PH7_XML_CDATA, /* Character data */ + PH7_XML_PI, /* Processing instruction */ + PH7_XML_DEF, /* Default (unused) */ + PH7_XML_UNPED, /* Unparsed entity (unused) */ + PH7_XML_ND, /* Notation declaration (unused) */ + PH7_XML_EER, /* External entity reference (unused) */ + PH7_XML_NS_START, /* Start namespace declaration */ + PH7_XML_NS_END, /* End namespace declaration */ + PH7_XML_DOCTYPE /* DOCTYPE directive */ }; -/* An instance of the following structure describe a working - * XML engine instance. +/* + * An instance of the following structure describes a working XML engine. + * The engine is the payload of the private `resource` field of an XmlReader + * instance; all transient SAX state lives here so the typed getters can read + * it both from inside a callback and after Parse() returns. */ typedef struct ph7_xml_engine ph7_xml_engine; struct ph7_xml_engine { - ph7_vm *pVm; /* VM that own this instance */ - ph7_context *pCtx; /* Call context */ - SyXMLParser sParser; /* Underlying XML parser */ - ph7_value aCB[XML_TOTAL_HANDLER]; /* User-defined callbacks */ - ph7_value sParserValue; /* ph7_value holding this instance which is forwarded - * as the first argument to the user callbacks. - */ - int ns_sep; /* Namespace separator */ - SyBlob sErr; /* Error message consumer */ - sxi32 iErrCode; /* Last error code */ - sxi32 iNest; /* Nesting level */ - sxu32 nLine; /* Last processed line */ - sxu32 nMagic; /* Magic number so that we avoid misuse */ + ph7_vm *pVm; /* VM that owns this instance */ + ph7_context *pCtx; /* Current call context */ + SyXMLParser sParser; /* Underlying SAX parser */ + ph7_value aCB[XML_TOTAL_HANDLER]; /* Convenience callbacks by event id */ + ph7_value sParserValue; /* Resource value holding this engine */ + ph7_value sReaderValue; /* XmlReader object, owned only across Parse() */ + ph7_value sHandler; /* IXmlHandler implementation, when installed */ + ph7_value sAttrs; /* Snapshot of the current element attributes */ + ph7_value sLocalName; /* Current element local name */ + ph7_value sNsUri; /* Current element namespace URI */ + ph7_value sPrefix; /* Current element prefix */ + /* Reserved: the public API forwards QName components separately and never + * concatenates URI + separator + local name, so this value is unused. */ + int ns_sep; + SyBlob sErr; /* Last SAX error message */ + sxi32 iErrCode; /* Last SAX error code */ + sxu32 nErrLine; /* Line of the last SAX error */ + sxu32 nErrCol; /* Column of the last SAX error */ + sxi32 iNest; /* Recursive-parse guard */ + sxu32 nCurLine; /* SyXMLRawStr.nLine of the current event */ + sxi64 iCurByte; /* Byte offset of the current token */ + sxu32 nCurCol; /* Column of the current token */ + sxi32 nDepth; /* Element nesting depth */ + int bEmptyElement; /* TRUE only while dispatching the start event of a self-closing tag; cleared on the end event */ + int bError; /* A SAX error was reported */ + int bAbort; /* A user handler requested an abort */ + sxu32 nMagic; /* Misuse guard */ }; -static void PH7_XML_ERROR_NONE_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_NO_MEMORY_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_SYNTAX_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_NO_ELEMENTS_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_INVALID_TOKEN_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_UNCLOSED_TOKEN_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_PARTIAL_CHAR_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_TAG_MISMATCH_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_DUPLICATE_ATTRIBUTE_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_JUNK_AFTER_DOC_ELEMENT_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_PARAM_ENTITY_REF_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_UNDEFINED_ENTITY_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_RECURSIVE_ENTITY_REF_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_ASYNC_ENTITY_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_BAD_CHAR_REF_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_BINARY_ENTITY_REF_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_MISPLACED_XML_PI_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_UNKNOWN_ENCODING_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_INCORRECT_ENCODING_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_UNCLOSED_CDATA_SECTION_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_ERROR_EXTERNAL_ENTITY_HANDLING_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_OPTION_CASE_FOLDING_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_OPTION_TARGET_ENCODING_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_OPTION_SKIP_TAGSTART_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_OPTION_SKIP_WHITE_Const(ph7_value *pVal, void *pUserData); -static void PH7_XML_SAX_IMP_Const(ph7_value *pVal, void *pUserData); -static int vm_builtin_xml_parser_create(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_parser_create_ns(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_parser_free(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_set_element_handler(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_set_character_data_handler(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_set_default_handler(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_set_end_namespace_decl_handler(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_set_start_namespace_decl_handler(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_set_processing_instruction_handler(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_set_unparsed_entity_decl_handler(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_set_notation_decl_handler(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_set_external_entity_ref_handler(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_get_current_line_number(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_get_current_byte_index(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_set_object(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_get_current_column_number(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_get_error_code(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_parse(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_parser_set_option(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_parser_get_option(ph7_context *pCtx, int nArg, ph7_value **apArg); -static int vm_builtin_xml_error_string(ph7_context *pCtx, int nArg, ph7_value **apArg); PH7_PRIVATE sxi32 initializeModule(ph7_vm *pVm, ph7_real *ver, SyString *desc); -static const ph7_builtin_constant xmlConstList[] = { - {"XML_ERROR_NONE", PH7_XML_ERROR_NONE_Const}, - {"XML_ERROR_NO_MEMORY", PH7_XML_ERROR_NO_MEMORY_Const}, - {"XML_ERROR_SYNTAX", PH7_XML_ERROR_SYNTAX_Const}, - {"XML_ERROR_NO_ELEMENTS", PH7_XML_ERROR_NO_ELEMENTS_Const}, - {"XML_ERROR_INVALID_TOKEN", PH7_XML_ERROR_INVALID_TOKEN_Const}, - {"XML_ERROR_UNCLOSED_TOKEN", PH7_XML_ERROR_UNCLOSED_TOKEN_Const}, - {"XML_ERROR_PARTIAL_CHAR", PH7_XML_ERROR_PARTIAL_CHAR_Const}, - {"XML_ERROR_TAG_MISMATCH", PH7_XML_ERROR_TAG_MISMATCH_Const}, - {"XML_ERROR_DUPLICATE_ATTRIBUTE", PH7_XML_ERROR_DUPLICATE_ATTRIBUTE_Const}, - {"XML_ERROR_JUNK_AFTER_DOC_ELEMENT", PH7_XML_ERROR_JUNK_AFTER_DOC_ELEMENT_Const}, - {"XML_ERROR_PARAM_ENTITY_REF", PH7_XML_ERROR_PARAM_ENTITY_REF_Const}, - {"XML_ERROR_UNDEFINED_ENTITY", PH7_XML_ERROR_UNDEFINED_ENTITY_Const}, - {"XML_ERROR_RECURSIVE_ENTITY_REF", PH7_XML_ERROR_RECURSIVE_ENTITY_REF_Const}, - {"XML_ERROR_ASYNC_ENTITY", PH7_XML_ERROR_ASYNC_ENTITY_Const}, - {"XML_ERROR_BAD_CHAR_REF", PH7_XML_ERROR_BAD_CHAR_REF_Const}, - {"XML_ERROR_BINARY_ENTITY_REF", PH7_XML_ERROR_BINARY_ENTITY_REF_Const}, - {"XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", PH7_XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF_Const}, - {"XML_ERROR_MISPLACED_XML_PI", PH7_XML_ERROR_MISPLACED_XML_PI_Const}, - {"XML_ERROR_UNKNOWN_ENCODING", PH7_XML_ERROR_UNKNOWN_ENCODING_Const}, - {"XML_ERROR_INCORRECT_ENCODING", PH7_XML_ERROR_INCORRECT_ENCODING_Const}, - {"XML_ERROR_UNCLOSED_CDATA_SECTION", PH7_XML_ERROR_UNCLOSED_CDATA_SECTION_Const}, - {"XML_ERROR_EXTERNAL_ENTITY_HANDLING", PH7_XML_ERROR_EXTERNAL_ENTITY_HANDLING_Const}, - {"XML_OPTION_CASE_FOLDING", PH7_XML_OPTION_CASE_FOLDING_Const}, - {"XML_OPTION_TARGET_ENCODING", PH7_XML_OPTION_TARGET_ENCODING_Const}, - {"XML_OPTION_SKIP_TAGSTART", PH7_XML_OPTION_SKIP_TAGSTART_Const}, - {"XML_OPTION_SKIP_WHITE", PH7_XML_OPTION_SKIP_WHITE_Const}, - {"XML_SAX_IMPL", PH7_XML_SAX_IMP_Const} -}; - -static const ph7_builtin_func xmlFuncList[] = { - {"xml_parser_create", vm_builtin_xml_parser_create }, - {"xml_parser_create_ns", vm_builtin_xml_parser_create_ns}, - {"xml_parser_free", vm_builtin_xml_parser_free }, - {"xml_set_element_handler", vm_builtin_xml_set_element_handler}, - {"xml_set_character_data_handler", vm_builtin_xml_set_character_data_handler}, - {"xml_set_default_handler", vm_builtin_xml_set_default_handler }, - {"xml_set_end_namespace_decl_handler", vm_builtin_xml_set_end_namespace_decl_handler}, - {"xml_set_start_namespace_decl_handler", vm_builtin_xml_set_start_namespace_decl_handler}, - {"xml_set_processing_instruction_handler", vm_builtin_xml_set_processing_instruction_handler}, - {"xml_set_unparsed_entity_decl_handler", vm_builtin_xml_set_unparsed_entity_decl_handler}, - {"xml_set_notation_decl_handler", vm_builtin_xml_set_notation_decl_handler}, - {"xml_set_external_entity_ref_handler", vm_builtin_xml_set_external_entity_ref_handler}, - {"xml_get_current_line_number", vm_builtin_xml_get_current_line_number}, - {"xml_get_current_byte_index", vm_builtin_xml_get_current_byte_index }, - {"xml_set_object", vm_builtin_xml_set_object}, - {"xml_get_current_column_number", vm_builtin_xml_get_current_column_number}, - {"xml_get_error_code", vm_builtin_xml_get_error_code }, - {"xml_parse", vm_builtin_xml_parse }, - {"xml_parser_set_option", vm_builtin_xml_parser_set_option}, - {"xml_parser_get_option", vm_builtin_xml_parser_get_option}, - {"xml_error_string", vm_builtin_xml_error_string } -}; - -#endif \ No newline at end of file +#endif