Add TextWriter, IOException, per-VM module data and pre-load imports; Add console module with Console class
This commit is contained in:
@@ -11,7 +11,7 @@ RCFLAGS = -O3 -s
|
||||
LDFLAGS =
|
||||
|
||||
# Flags to enable sanitize checker
|
||||
SFLAGS = -fsanitize=address -fsanitize=leak
|
||||
#SFLAGS = -fsanitize=address -fsanitize=leak
|
||||
|
||||
# Destination directory
|
||||
DESTDIR ?= $(realpath .)/binary
|
||||
@@ -117,6 +117,7 @@ SAPI := $(subst /,,$(subst sapi/,,$(dir $(wildcard sapi/*/))))
|
||||
TEST_DIR := tests
|
||||
TEST_EXT := aer
|
||||
TESTS := $(subst .$(TEST_EXT),.test,$(wildcard $(TEST_DIR)/*.$(TEST_EXT)))
|
||||
ERR_TESTS := $(subst .$(TEST_EXT),.errtest,$(wildcard $(TEST_DIR)/errors/*.$(TEST_EXT)))
|
||||
|
||||
|
||||
.SUFFIXES:
|
||||
@@ -126,12 +127,12 @@ debug: export CFLAGS := $(CFLAGS) $(DCFLAGS)
|
||||
debug: engine sapi modules
|
||||
release: export CFLAGS := $(CFLAGS) $(RCFLAGS)
|
||||
release: engine sapi modules
|
||||
sanitize: export CFLAGS := $(CFLAGS) $(DCFLAGS) $(SFLAGS)
|
||||
sanitize: $(eval LDFLAGS := $(LDFLAGS) $(SFLAGS))
|
||||
sanitize: engine sapi modules
|
||||
#sanitize: export CFLAGS := $(CFLAGS) $(DCFLAGS) $(SFLAGS)
|
||||
#sanitize: $(eval LDFLAGS := $(LDFLAGS) $(SFLAGS))
|
||||
#sanitize: engine sapi modules
|
||||
|
||||
engine: $(ENGINE_OBJS)
|
||||
$(CC) -o $(BUILD_DIR)/lib$(BINARY)$(LIBSUFFIX) $(LDFLAGS) $(LIBS) -shared $(ENGINE_OBJS)
|
||||
$(CC) -o $(BUILD_DIR)/lib$(BINARY)$(LIBSUFFIX) $(LDFLAGS) -shared $(ENGINE_OBJS) $(LIBS)
|
||||
|
||||
modules: $(MODULE)
|
||||
|
||||
@@ -147,7 +148,7 @@ $(MODULE):
|
||||
$(eval MODULE_MAKE := $(MODULE_SRCS:.c=.o))
|
||||
$(eval MODULE_OBJS := $(addprefix $(BUILD_DIR)/,$(MODULE_MAKE)))
|
||||
$(eval MODULE_PROG := $(MODULE_DIRS)$(LIBSUFFIX))
|
||||
$(MAKE) $(MODULE_OBJS)
|
||||
$(MAKE) $(MODULE_OBJS) CFLAGS='$(CFLAGS)'
|
||||
$(CC) -o $(BUILD_DIR)/$(MODULE_PROG) $(LDFLAGS) -shared $(MODULE_OBJS)
|
||||
|
||||
$(SAPI):
|
||||
@@ -156,27 +157,14 @@ $(SAPI):
|
||||
$(eval SAPI_MAKE := $(SAPI_SRCS:.c=.o))
|
||||
$(eval SAPI_OBJS := $(addprefix $(BUILD_DIR)/,$(SAPI_MAKE)))
|
||||
$(eval SAPI_PROG := $(subst -cli,,$(BINARY)-$(SAPI_DIRS))$(EXESUFFIX))
|
||||
$(MAKE) $(SAPI_OBJS)
|
||||
$(CC) -o $(BUILD_DIR)/$(SAPI_PROG) $(LDFLAGS) $(LIBFLAGS) $(SAPI_OBJS)
|
||||
$(MAKE) $(SAPI_OBJS) CFLAGS='$(CFLAGS)'
|
||||
$(CC) -o $(BUILD_DIR)/$(SAPI_PROG) $(LDFLAGS) $(SAPI_OBJS) $(LIBFLAGS)
|
||||
|
||||
%.test: %.exp %.$(TEST_EXT)
|
||||
@$(MD) ${BUILD_DIR}/${TEST_DIR}
|
||||
@echo -n "Executing test: $*.$(TEST_EXT) ... "
|
||||
@if [ "x`echo $* | grep args`" != "x" ]; \
|
||||
then \
|
||||
binary/$(BINARY)$(EXESUFFIX) $*.$(TEST_EXT) - arg1 arg2 arg3 arg4 2>&1 >$(BUILD_DIR)/$*.out; \
|
||||
else \
|
||||
binary/$(BINARY)$(EXESUFFIX) $*.$(TEST_EXT) 2>&1 >$(BUILD_DIR)/$*.out; \
|
||||
fi
|
||||
@if [ "x`diff -qbu $*.exp $(BUILD_DIR)/$*.out`" != "x" ]; \
|
||||
then \
|
||||
echo "ERROR!"; \
|
||||
diff -u $*.exp $(BUILD_DIR)/$*.out; \
|
||||
rm -f $(BUILD_DIR)/$(TEST_DIR)/*.out \
|
||||
exit 1; \
|
||||
fi;
|
||||
@rm -f $(BUILD_DIR)/$(TEST_DIR)/*.out
|
||||
@echo "OK!"
|
||||
%.test: %.$(TEST_EXT)
|
||||
python3 $(TEST_DIR)/run_tests.py --binary binary/$(BINARY)$(EXESUFFIX) $*.$(TEST_EXT)
|
||||
|
||||
$(TEST_DIR)/errors/%.errtest: $(TEST_DIR)/errors/%.$(TEST_EXT)
|
||||
python3 $(TEST_DIR)/run_tests.py --binary binary/$(BINARY)$(EXESUFFIX) $(TEST_DIR)/errors/$*.$(TEST_EXT)
|
||||
|
||||
clean:
|
||||
$(RM) $(BUILD_DIR)
|
||||
@@ -189,5 +177,5 @@ install: engine modules sapi
|
||||
style:
|
||||
astyle $(ASTYLE_FLAGS) --recursive ./*.c,*.h
|
||||
|
||||
tests: $(TESTS)
|
||||
|
||||
tests:
|
||||
python3 $(TEST_DIR)/run_tests.py --binary binary/$(BINARY)$(EXESUFFIX)
|
||||
|
||||
@@ -3786,87 +3786,6 @@ static int PH7_builtin_sprintf(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
PH7_InputFormat(sprintfConsumer, pCtx, zFormat, nLen, nArg, apArg, 0, FALSE);
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* Callback [i.e: Formatted input consumer] of the printf function.
|
||||
*/
|
||||
static int printfConsumer(ph7_context *pCtx, const char *zInput, int nLen, void *pUserData) {
|
||||
ph7_int64 *pCounter = (ph7_int64 *)pUserData;
|
||||
/* Call the VM output consumer directly */
|
||||
ph7_context_output(pCtx, zInput, nLen);
|
||||
/* Increment counter */
|
||||
*pCounter += nLen;
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* int64 printf(string $format[,mixed $args[,mixed $... ]])
|
||||
* Output a formatted string.
|
||||
* Parameters
|
||||
* $format
|
||||
* See sprintf() for a description of format.
|
||||
* Return
|
||||
* The length of the outputted string.
|
||||
*/
|
||||
static int PH7_builtin_printf(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
ph7_int64 nCounter = 0;
|
||||
const char *zFormat;
|
||||
int nLen;
|
||||
if(nArg < 1 || !ph7_value_is_string(apArg[0])) {
|
||||
/* Missing/Invalid arguments, return 0 */
|
||||
ph7_result_int(pCtx, 0);
|
||||
return PH7_OK;
|
||||
}
|
||||
/* Extract the string format */
|
||||
zFormat = ph7_value_to_string(apArg[0], &nLen);
|
||||
if(nLen < 1) {
|
||||
/* Empty string */
|
||||
ph7_result_int(pCtx, 0);
|
||||
return PH7_OK;
|
||||
}
|
||||
/* Format the string */
|
||||
PH7_InputFormat(printfConsumer, pCtx, zFormat, nLen, nArg, apArg, (void *)&nCounter, FALSE);
|
||||
/* Return the length of the outputted string */
|
||||
ph7_result_int64(pCtx, nCounter);
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* int vprintf(string $format,array $args)
|
||||
* Output a formatted string.
|
||||
* Parameters
|
||||
* $format
|
||||
* See sprintf() for a description of format.
|
||||
* Return
|
||||
* The length of the outputted string.
|
||||
*/
|
||||
static int PH7_builtin_vprintf(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
ph7_int64 nCounter = 0;
|
||||
const char *zFormat;
|
||||
ph7_hashmap *pMap;
|
||||
SySet sArg;
|
||||
int nLen, n;
|
||||
if(nArg < 2 || !ph7_value_is_string(apArg[0]) || !ph7_value_is_array(apArg[1])) {
|
||||
/* Missing/Invalid arguments, return 0 */
|
||||
ph7_result_int(pCtx, 0);
|
||||
return PH7_OK;
|
||||
}
|
||||
/* Extract the string format */
|
||||
zFormat = ph7_value_to_string(apArg[0], &nLen);
|
||||
if(nLen < 1) {
|
||||
/* Empty string */
|
||||
ph7_result_int(pCtx, 0);
|
||||
return PH7_OK;
|
||||
}
|
||||
/* Point to the hashmap */
|
||||
pMap = (ph7_hashmap *)apArg[1]->x.pOther;
|
||||
/* Extract arguments from the hashmap */
|
||||
n = PH7_HashmapValuesToSet(pMap, &sArg);
|
||||
/* Format the string */
|
||||
PH7_InputFormat(printfConsumer, pCtx, zFormat, nLen, n, (ph7_value **)SySetBasePtr(&sArg), (void *)&nCounter, TRUE);
|
||||
/* Return the length of the outputted string */
|
||||
ph7_result_int64(pCtx, nCounter);
|
||||
/* Release the container */
|
||||
SySetRelease(&sArg);
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* int vsprintf(string $format,array $args)
|
||||
* Output a formatted string.
|
||||
@@ -7457,8 +7376,6 @@ static const ph7_builtin_func aBuiltInFunc[] = {
|
||||
{ "str_repeat", PH7_builtin_str_repeat },
|
||||
{ "nl2br", PH7_builtin_nl2br },
|
||||
{ "sprintf", PH7_builtin_sprintf },
|
||||
{ "printf", PH7_builtin_printf },
|
||||
{ "vprintf", PH7_builtin_vprintf },
|
||||
{ "vsprintf", PH7_builtin_vsprintf },
|
||||
{ "size_format", PH7_builtin_size_format},
|
||||
{ "md5", PH7_builtin_md5 },
|
||||
|
||||
@@ -302,6 +302,136 @@ static sxi32 StdConvert(ph7_context *pCtx, sxi32 nArg, ph7_value **apArg) {
|
||||
return rc == PH7_OK ? ph7_result_value(pCtx, pValue) : rc;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* IOException: a core Exception subclass carrying an error code. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
static const char *IoErrorDescription(int nErr) {
|
||||
switch(nErr) {
|
||||
case 0: return "No error";
|
||||
case 1: return "Invalid argument";
|
||||
case 2: return "I/O error";
|
||||
default: return "Unknown error code";
|
||||
}
|
||||
}
|
||||
/* Stamp file/line with the first script frame of the active call stack.
|
||||
* Native frames ([NATIVE], line 0) are skipped so a catch(Exception $e)
|
||||
* observes the script location that raised the error. */
|
||||
static ph7_value *IoInstField(ph7_class_instance *pInst, const char *zName) {
|
||||
SyString s;
|
||||
if(pInst == 0) {
|
||||
return 0;
|
||||
}
|
||||
SyStringInitFromBuf(&s, zName, (sxu32)SyStrlen(zName));
|
||||
return PH7_ClassInstanceFetchAttr(pInst, &s);
|
||||
}
|
||||
static void IOExceptionStamp(ph7_vm *pVm, ph7_class_instance *pInst) {
|
||||
ph7_value *pField;
|
||||
SySet sTrace;
|
||||
VmDebugTrace *pTrace;
|
||||
if(pInst == 0 || VmExtractDebugTrace(pVm, &sTrace) != SXRET_OK) {
|
||||
return;
|
||||
}
|
||||
while(SySetGetNextEntry(&sTrace, (void **)&pTrace) == SXRET_OK) {
|
||||
if(pTrace->pFile == 0 || pTrace->nLine == 0) {
|
||||
continue;
|
||||
}
|
||||
if(pTrace->pFile->nByte == sizeof("[NATIVE]") - 1 &&
|
||||
SyMemcmp(pTrace->pFile->zString, "[NATIVE]", sizeof("[NATIVE]") - 1) == 0) {
|
||||
continue;
|
||||
}
|
||||
pField = IoInstField(pInst, "file");
|
||||
if(pField) {
|
||||
PH7_MemObjRelease(pField);
|
||||
PH7_MemObjInit(pVm, pField);
|
||||
(void)ph7_value_string(pField, pTrace->pFile->zString, (int)pTrace->pFile->nByte);
|
||||
}
|
||||
pField = IoInstField(pInst, "line");
|
||||
if(pField) {
|
||||
(void)ph7_value_int64(pField, (ph7_int64)pTrace->nLine);
|
||||
}
|
||||
break;
|
||||
}
|
||||
SySetRelease(&sTrace);
|
||||
}
|
||||
static sxi32 IOExceptionConstruct(ph7_context *pCtx, sxi32 nArg, ph7_value **apArg) {
|
||||
ph7_value *pResult = ph7_context_new_scalar(pCtx);
|
||||
ph7_value *pThis = ph7_context_this(pCtx);
|
||||
ph7_class_instance *pInst;
|
||||
sxi32 rc;
|
||||
if(pResult == 0) {
|
||||
return PH7_NOMEM;
|
||||
}
|
||||
/* Let the base Exception constructor own message/code/file/line/trace.
|
||||
* parent:: is required: a plain dispatch would resolve back here. */
|
||||
rc = ph7_context_parent(pCtx, "__construct", nArg > 2 ? 3 : 2, apArg, pResult);
|
||||
if(rc != PH7_OK) {
|
||||
return rc;
|
||||
}
|
||||
if(pThis && pThis->x.pOther) {
|
||||
pInst = (ph7_class_instance *)pThis->x.pOther;
|
||||
IOExceptionStamp(pCtx->pVm, pInst);
|
||||
}
|
||||
return PH7_OK;
|
||||
}
|
||||
static sxi32 IOExceptionDescription(ph7_context *pCtx, sxi32 nArg, ph7_value **apArg) {
|
||||
int nErr = nArg > 0 ? ph7_value_to_int(apArg[0]) : -1;
|
||||
return ph7_result_string(pCtx, IoErrorDescription(nErr), -1);
|
||||
}
|
||||
/* Core-owned IOException throw used by both the Console module and TextWriter
|
||||
* so the same validation produces the same exception on every call path.
|
||||
* The constructor stamps file/line; the pending transfer is left for the VM
|
||||
* unwinder. Full cleanup on every failure path. */
|
||||
PH7_PRIVATE sxi32 PH7_VmThrowIoException(ph7_context *pCtx, int nCode, const char *zMsg) {
|
||||
ph7_vm *pVm = pCtx->pVm;
|
||||
ph7_class *pClass;
|
||||
ph7_class_instance *pInst;
|
||||
ph7_class_method *pCons;
|
||||
ph7_value *pResult, *pObj, *apArg[2];
|
||||
sxi32 rc;
|
||||
if(pVm->iPendingTransfer) {
|
||||
return PH7_EXCEPTION;
|
||||
}
|
||||
pClass = PH7_VmExtractClass(pVm, "IOException", sizeof("IOException") - 1, TRUE);
|
||||
if(pClass == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pInst = PH7_NewClassInstance(pVm, pClass);
|
||||
if(pInst == 0) {
|
||||
PH7_VmMemoryError(pVm);
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pResult = ph7_context_new_scalar(pCtx);
|
||||
apArg[0] = ph7_context_new_scalar(pCtx);
|
||||
apArg[1] = ph7_context_new_scalar(pCtx);
|
||||
pObj = ph7_context_new_scalar(pCtx);
|
||||
if(pResult == 0 || apArg[0] == 0 || apArg[1] == 0 || pObj == 0) {
|
||||
PH7_ClassInstanceUnref(pInst);
|
||||
PH7_VmMemoryError(pVm);
|
||||
return PH7_ABORT;
|
||||
}
|
||||
ph7_value_string(apArg[0], zMsg, -1);
|
||||
ph7_value_int(apArg[1], nCode);
|
||||
pCons = PH7_ClassExtractMethod(pClass, "__construct", sizeof("__construct") - 1);
|
||||
if(pCons) {
|
||||
rc = PH7_VmCallClassMethod(pVm, pInst, pCons, pResult, 2, apArg);
|
||||
if(pInst->iRef < 1) {
|
||||
pInst->iRef = 1;
|
||||
}
|
||||
if(rc != PH7_OK) {
|
||||
PH7_ClassInstanceUnref(pInst);
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
if(pInst->iRef < 1) {
|
||||
pInst->iRef = 1;
|
||||
}
|
||||
PH7_MemObjRelease(pObj);
|
||||
pObj->x.pOther = pInst;
|
||||
MemObjSetType(pObj, MEMOBJ_OBJ);
|
||||
rc = ph7_result_value(pCtx, pObj);
|
||||
return rc == PH7_OK ? PH7_EXCEPTION : rc;
|
||||
}
|
||||
|
||||
PH7_PRIVATE sxi32 PH7_VmInstallBuiltinClasses(ph7_vm *pVm) {
|
||||
ph7_value *apValue[4] = { 0, 0, 0, 0 };
|
||||
static const ph7_type_def aConversion[] = {
|
||||
@@ -376,14 +506,49 @@ PH7_PRIVATE sxi32 PH7_VmInstallBuiltinClasses(ph7_vm *pVm) {
|
||||
{ .zName = "__toString", .sResult = { PH7_TYPE_STRING, 0, 0 }, .xFunc = StdConvert, .pUserData = (void *)&aConversion[3] },
|
||||
{ .zName = "__construct", .sResult = { PH7_TYPE_VOID, 0, 0 }, .aParam = aValueParam, .nParam = 1, .xFunc = StdConstruct, .iFlags = PH7_MEMBER_PRIVATE }
|
||||
};
|
||||
static ph7_constant_def aIoConst[] = {
|
||||
{ .zName = "ERROR_NONE", .iFlags = PH7_MEMBER_PUBLIC },
|
||||
{ .zName = "ERROR_ARGUMENT", .iFlags = PH7_MEMBER_PUBLIC },
|
||||
{ .zName = "ERROR_IO", .iFlags = PH7_MEMBER_PUBLIC }
|
||||
};
|
||||
static ph7_param_def aIoParam[] = {
|
||||
{ .zName = "message", .sType = { PH7_TYPE_STRING, 0, 0 } },
|
||||
{ .zName = "code", .sType = { PH7_TYPE_INT, 0, 0 } }
|
||||
};
|
||||
static const ph7_param_def aIoDescParam[] = {
|
||||
{ .zName = "code", .sType = { PH7_TYPE_INT, 0, 0 } }
|
||||
};
|
||||
static ph7_param_def aPrintLineParam[] = {
|
||||
{ .zName = "value", .sType = { PH7_TYPE_MIXED, 0, 0 } }
|
||||
};
|
||||
static const ph7_method_def aIoMethod[] = {
|
||||
{ .zName = "__construct", .sResult = { PH7_TYPE_VOID, 0, 0 }, .aParam = aIoParam, .nParam = 2, .xFunc = IOExceptionConstruct },
|
||||
{ .zName = "GetDescription", .sResult = { PH7_TYPE_STRING, 0, 0 }, .aParam = aIoDescParam, .nParam = 1, .xFunc = IOExceptionDescription,
|
||||
.iFlags = PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC }
|
||||
};
|
||||
static const ph7_field_def aTextWriterField[] = {
|
||||
{ .zName = "handle", .sType = { PH7_TYPE_RESOURCE, 0, 0 }, .iFlags = PH7_MEMBER_PRIVATE }
|
||||
};
|
||||
static const ph7_method_def aTextWriterMethod[] = {
|
||||
{ .zName = "__construct", .sResult = { PH7_TYPE_VOID, 0, 0 }, .aParam = aValueParam, .nParam = 1, .xFunc = TextWriterConstruct, .iFlags = PH7_MEMBER_PRIVATE },
|
||||
{ .zName = "__destruct", .sResult = { PH7_TYPE_VOID, 0, 0 }, .xFunc = TextWriterDestruct },
|
||||
{ .zName = "__clone", .sResult = { PH7_TYPE_VOID, 0, 0 }, .xFunc = TextWriterClone, .iFlags = PH7_MEMBER_PRIVATE },
|
||||
{ .zName = "Print", .sResult = { PH7_TYPE_VOID, 0, 0 }, .aParam = aValueParam, .nParam = 1, .xFunc = TextWriterPrint, .iFlags = PH7_MEMBER_PUBLIC | PH7_MEMBER_VARIADIC },
|
||||
{ .zName = "PrintLine", .sResult = { PH7_TYPE_VOID, 0, 0 }, .aParam = aPrintLineParam, .nParam = 1, .xFunc = TextWriterPrintLine, .iFlags = PH7_MEMBER_PUBLIC | PH7_MEMBER_VARIADIC },
|
||||
{ .zName = "Flush", .sResult = { PH7_TYPE_VOID, 0, 0 }, .xFunc = TextWriterFlush }
|
||||
};
|
||||
static const char *const aIoBase[] = { "Exception" };
|
||||
ph7_class_def aClass[] = {
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "Exception", .aField = aExceptionField, .nField = SX_ARRAYSIZE(aExceptionField), .aMethod = aExceptionMethod, .nMethod = SX_ARRAYSIZE(aExceptionMethod) },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "IOException", .aConstant = aIoConst, .nConstant = SX_ARRAYSIZE(aIoConst), .aMethod = aIoMethod, .nMethod = SX_ARRAYSIZE(aIoMethod), .azBase = aIoBase, .nBase = 1 },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "TextWriter", .aField = aTextWriterField, .nField = SX_ARRAYSIZE(aTextWriterField), .aMethod = aTextWriterMethod, .nMethod = SX_ARRAYSIZE(aTextWriterMethod) },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "Iterator", .aMethod = aIteratorMethod, .nMethod = SX_ARRAYSIZE(aIteratorMethod), .iFlags = PH7_DECL_INTERFACE },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "IteratorAggregate", .aMethod = aAggregateMethod, .nMethod = SX_ARRAYSIZE(aAggregateMethod), .iFlags = PH7_DECL_INTERFACE },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "Serializable", .aMethod = aSerializableMethod, .nMethod = SX_ARRAYSIZE(aSerializableMethod), .iFlags = PH7_DECL_INTERFACE },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "Directory", .aField = aDirectoryField, .nField = SX_ARRAYSIZE(aDirectoryField), .aMethod = aDirectoryMethod, .nMethod = SX_ARRAYSIZE(aDirectoryMethod) },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "stdClass", .aField = aStdField, .nField = SX_ARRAYSIZE(aStdField), .aMethod = aStdMethod, .nMethod = SX_ARRAYSIZE(aStdMethod) }
|
||||
};
|
||||
ph7_value *apIoValue[SX_ARRAYSIZE(aIoConst)] = { 0 };
|
||||
sxi32 rc = PH7_NOMEM;
|
||||
sxu32 n;
|
||||
for(n = 0; n < SX_ARRAYSIZE(apValue); n++) {
|
||||
@@ -392,6 +557,14 @@ PH7_PRIVATE sxi32 PH7_VmInstallBuiltinClasses(ph7_vm *pVm) {
|
||||
goto Cleanup;
|
||||
}
|
||||
}
|
||||
for(n = 0; n < SX_ARRAYSIZE(apIoValue); n++) {
|
||||
apIoValue[n] = ph7_new_scalar(pVm);
|
||||
if(apIoValue[n] == 0) {
|
||||
goto Cleanup;
|
||||
}
|
||||
ph7_value_int(apIoValue[n], (int)n);
|
||||
aIoConst[n].pValue = apIoValue[n];
|
||||
}
|
||||
rc = ph7_value_string(apValue[0], "Unknown exception", -1);
|
||||
if(rc == PH7_OK) {
|
||||
rc = ph7_value_string(apValue[1], "", 0);
|
||||
@@ -407,6 +580,9 @@ PH7_PRIVATE sxi32 PH7_VmInstallBuiltinClasses(ph7_vm *pVm) {
|
||||
aExceptionParam[0].pDefault = apValue[1];
|
||||
aExceptionParam[1].pDefault = apValue[2];
|
||||
aExceptionParam[2].pDefault = apValue[3];
|
||||
aIoParam[0].pDefault = apValue[1];
|
||||
aIoParam[1].pDefault = apValue[2];
|
||||
aPrintLineParam[0].pDefault = apValue[1];
|
||||
for(n = 0; n < SX_ARRAYSIZE(aClass); n++) {
|
||||
rc = ph7_create_class(pVm, &aClass[n]);
|
||||
if(rc != PH7_OK) {
|
||||
@@ -414,6 +590,12 @@ PH7_PRIVATE sxi32 PH7_VmInstallBuiltinClasses(ph7_vm *pVm) {
|
||||
}
|
||||
}
|
||||
Cleanup:
|
||||
for(n = 0; n < SX_ARRAYSIZE(apIoValue); n++) {
|
||||
if(apIoValue[n]) {
|
||||
ph7_release_value(pVm, apIoValue[n]);
|
||||
aIoConst[n].pValue = 0;
|
||||
}
|
||||
}
|
||||
for(n = 0; n < SX_ARRAYSIZE(apValue); n++) {
|
||||
if(apValue[n]) {
|
||||
ph7_release_value(pVm, apValue[n]);
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* @PROJECT PH7 Engine for the AerScript Interpreter
|
||||
* @COPYRIGHT See COPYING in the top level directory
|
||||
* @FILE engine/textwriter.c
|
||||
* @DESCRIPTION TextWriter core class support and its C API
|
||||
* @DEVELOPERS Rafal Kupiec <belliash@codingworkshop.eu.org>
|
||||
*/
|
||||
#include "ph7int.h"
|
||||
|
||||
/* A backend is stored as a resource in TextWriter->handle. The wrapper is
|
||||
* refcounted because cloning an instance copies the resource pointer: each
|
||||
* live instance owns one reference and releases it from its destructor. */
|
||||
typedef struct text_writer_backend {
|
||||
ph7_text_writer_methods sMethods;
|
||||
void *pUserData;
|
||||
int nRef;
|
||||
} text_writer_backend;
|
||||
|
||||
/* Adapter between PH7_InputFormat's consumer and a backend xWrite callback. */
|
||||
typedef struct text_writer_sink {
|
||||
int (*xWrite)(void *, const void *, unsigned int);
|
||||
void *pUserData;
|
||||
} text_writer_sink;
|
||||
|
||||
static int TextWriterSink(ph7_context *pCtx, const char *zData, int nLen, void *pUserData) {
|
||||
text_writer_sink *pSink = (text_writer_sink *)pUserData;
|
||||
SXUNUSED(pCtx);
|
||||
if(nLen > 0 && pSink->xWrite) {
|
||||
return pSink->xWrite(pSink->pUserData, zData, (unsigned int)nLen);
|
||||
}
|
||||
return SXRET_OK;
|
||||
}
|
||||
|
||||
/* Fetch the backend wrapper owned by the current TextWriter instance. */
|
||||
static text_writer_backend *TextWriterFetch(ph7_context *pCtx) {
|
||||
ph7_class_instance *pInst;
|
||||
ph7_value *pThis, *pField;
|
||||
SyString sName;
|
||||
pThis = ph7_context_this(pCtx);
|
||||
if(pThis == 0 || (pThis->nType & MEMOBJ_OBJ) == 0 || pThis->x.pOther == 0) {
|
||||
return 0;
|
||||
}
|
||||
pInst = (ph7_class_instance *)pThis->x.pOther;
|
||||
SyStringInitFromBuf(&sName, "handle", sizeof("handle") - 1);
|
||||
pField = PH7_ClassInstanceFetchAttr(pInst, &sName);
|
||||
if(pField == 0 || (pField->nType & MEMOBJ_RES) == 0 || pField->x.pOther == 0) {
|
||||
return 0;
|
||||
}
|
||||
return (text_writer_backend *)pField->x.pOther;
|
||||
}
|
||||
|
||||
/* Single shared implementation of the Console/TextWriter print rule: with one
|
||||
* argument the value is written literally (a lone '%' is ordinary text), with
|
||||
* several the first argument is the format string. bLine appends the EOL. */
|
||||
int ph7_text_writer_emit(ph7_context *pCtx,
|
||||
int (*xWrite)(void *, const void *, unsigned int),
|
||||
void *pUserData, int nArg, ph7_value **apArg, int bLine) {
|
||||
text_writer_sink sSink;
|
||||
const char *zFormat;
|
||||
int nByte, rc;
|
||||
/* Single rule for every caller (Console::Print and TextWriter::Print):
|
||||
* with several arguments the first one must be a string format. */
|
||||
if(nArg > 1 && !ph7_value_is_string(apArg[0])) {
|
||||
return PH7_VmThrowIoException(pCtx, 1, "Format must be a string");
|
||||
}
|
||||
if(nArg < 1) {
|
||||
rc = SXRET_OK;
|
||||
} else if(nArg == 1) {
|
||||
zFormat = ph7_value_to_string(apArg[0], &nByte);
|
||||
if(pCtx->pVm->iPendingTransfer) {
|
||||
return pCtx->pVm->iPendingTransfer;
|
||||
}
|
||||
rc = xWrite && nByte > 0 ? xWrite(pUserData, zFormat, (unsigned int)nByte) : SXRET_OK;
|
||||
} else {
|
||||
sSink.xWrite = xWrite;
|
||||
sSink.pUserData = pUserData;
|
||||
zFormat = ph7_value_to_string(apArg[0], &nByte);
|
||||
if(pCtx->pVm->iPendingTransfer) {
|
||||
return pCtx->pVm->iPendingTransfer;
|
||||
}
|
||||
rc = PH7_InputFormat(TextWriterSink, pCtx, zFormat, nByte, nArg, apArg, &sSink, FALSE);
|
||||
}
|
||||
if(rc == SXRET_OK && bLine) {
|
||||
#ifdef __WINNT__
|
||||
static const char zEOL[] = "\r\n";
|
||||
#else
|
||||
static const char zEOL[] = "\n";
|
||||
#endif
|
||||
if(xWrite && xWrite(pUserData, zEOL, (unsigned int)(sizeof(zEOL) - 1)) != SXRET_OK) {
|
||||
rc = PH7_ABORT;
|
||||
}
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* Create a TextWriter instance around a backend and store it in pResult. */
|
||||
int ph7_text_writer_new(ph7_context *pCtx, const ph7_text_writer_methods *pMethods,
|
||||
void *pUserData, ph7_value *pResult) {
|
||||
ph7_vm *pVm = pCtx->pVm;
|
||||
text_writer_backend *pBackend;
|
||||
ph7_class *pClass;
|
||||
ph7_class_instance *pInst;
|
||||
ph7_value *pField;
|
||||
SyString sName;
|
||||
pClass = PH7_VmExtractClass(pVm, "TextWriter", sizeof("TextWriter") - 1, TRUE);
|
||||
if(pClass == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pBackend = (text_writer_backend *)SyMemBackendAlloc(&pVm->sAllocator, sizeof(text_writer_backend));
|
||||
if(pBackend == 0) {
|
||||
PH7_VmMemoryError(pVm);
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pBackend->sMethods = *pMethods;
|
||||
pBackend->pUserData = pUserData;
|
||||
pBackend->nRef = 1;
|
||||
pInst = PH7_NewClassInstance(pVm, pClass);
|
||||
if(pInst == 0) {
|
||||
SyMemBackendFree(&pVm->sAllocator, pBackend);
|
||||
PH7_VmMemoryError(pVm);
|
||||
return PH7_ABORT;
|
||||
}
|
||||
SyStringInitFromBuf(&sName, "handle", sizeof("handle") - 1);
|
||||
pField = PH7_ClassInstanceFetchAttr(pInst, &sName);
|
||||
if(pField == 0) {
|
||||
PH7_ClassInstanceUnref(pInst);
|
||||
SyMemBackendFree(&pVm->sAllocator, pBackend);
|
||||
PH7_VmMemoryError(pVm);
|
||||
return PH7_ABORT;
|
||||
}
|
||||
ph7_value_resource(pField, pBackend);
|
||||
PH7_MemObjRelease(pResult);
|
||||
pResult->x.pOther = pInst;
|
||||
MemObjSetType(pResult, MEMOBJ_OBJ);
|
||||
return PH7_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Native callbacks for the core TextWriter class */
|
||||
/* ------------------------------------------------------------------ */
|
||||
int TextWriterConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
ph7_class_instance *pInst;
|
||||
ph7_value *pField;
|
||||
SyString sName;
|
||||
ph7_value *pThis = ph7_context_this(pCtx);
|
||||
if(pThis == 0 || (pThis->nType & MEMOBJ_OBJ) == 0 || pThis->x.pOther == 0 || nArg < 1) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pInst = (ph7_class_instance *)pThis->x.pOther;
|
||||
SyStringInitFromBuf(&sName, "handle", sizeof("handle") - 1);
|
||||
pField = PH7_ClassInstanceFetchAttr(pInst, &sName);
|
||||
if(pField == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
return ph7_value_resource(pField, ph7_value_to_resource(apArg[0])) == PH7_OK ? PH7_OK : PH7_ABORT;
|
||||
}
|
||||
|
||||
int TextWriterDestruct(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
text_writer_backend *pBackend = TextWriterFetch(pCtx);
|
||||
ph7_vm *pVm = pCtx->pVm;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
if(pBackend == 0) {
|
||||
return PH7_OK;
|
||||
}
|
||||
ph7_class_instance *pInst;
|
||||
ph7_value *pField;
|
||||
SyString sName;
|
||||
/* Drop this instance's reference unconditionally: an explicit second
|
||||
* __destruct() must be a no-op instead of a use-after-free, and a clone
|
||||
* that outlives this instance must not keep a dangling handle. Each
|
||||
* instance owns its own field, so a co-owner's pointer is untouched. */
|
||||
pInst = (ph7_class_instance *)ph7_context_this(pCtx)->x.pOther;
|
||||
SyStringInitFromBuf(&sName, "handle", sizeof("handle") - 1);
|
||||
pField = PH7_ClassInstanceFetchAttr(pInst, &sName);
|
||||
if(pField) {
|
||||
ph7_value_resource(pField, 0);
|
||||
}
|
||||
if(--pBackend->nRef <= 0) {
|
||||
if(pBackend->sMethods.xRelease) {
|
||||
pBackend->sMethods.xRelease(pBackend->pUserData);
|
||||
}
|
||||
SyMemBackendFree(&pVm->sAllocator, pBackend);
|
||||
}
|
||||
return PH7_OK;
|
||||
}
|
||||
|
||||
int TextWriterClone(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
text_writer_backend *pBackend = TextWriterFetch(pCtx);
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
/* Clone copies the resource pointer; own a reference for the new instance. */
|
||||
if(pBackend) {
|
||||
pBackend->nRef++;
|
||||
}
|
||||
return PH7_OK;
|
||||
}
|
||||
|
||||
static int TextWriterEmitThis(ph7_context *pCtx, int nArg, ph7_value **apArg, int bLine) {
|
||||
text_writer_backend *pBackend = TextWriterFetch(pCtx);
|
||||
if(pBackend == 0 || pBackend->sMethods.xWrite == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
return ph7_text_writer_emit(pCtx, pBackend->sMethods.xWrite, pBackend->pUserData,
|
||||
nArg, apArg, bLine);
|
||||
}
|
||||
|
||||
int TextWriterPrint(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
return TextWriterEmitThis(pCtx, nArg, apArg, 0);
|
||||
}
|
||||
|
||||
int TextWriterPrintLine(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
return TextWriterEmitThis(pCtx, nArg, apArg, 1);
|
||||
}
|
||||
|
||||
int TextWriterFlush(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
text_writer_backend *pBackend = TextWriterFetch(pCtx);
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
if(pBackend == 0) {
|
||||
return PH7_OK;
|
||||
}
|
||||
if(pBackend->sMethods.xFlush) {
|
||||
return pBackend->sMethods.xFlush(pBackend->pUserData);
|
||||
}
|
||||
return SXRET_OK;
|
||||
}
|
||||
+125
-5
@@ -7799,6 +7799,12 @@ struct ph7_stream_data {
|
||||
void *pHandle; /* Stream handle */
|
||||
ph7_output_consumer sConsumer; /* VM output consumer */
|
||||
} x;
|
||||
/* One-byte-at-a-time look-ahead from Console::Read() must be able to give
|
||||
* an unused byte back to the shared stdin stream, otherwise fgets()/fread()
|
||||
* would silently lose data. Served before any real read. */
|
||||
int nUnread; /* Number of pending bytes */
|
||||
int iUnread; /* Index of the next pending byte */
|
||||
unsigned char aUnread[4]; /* Pending bytes, in stream order */
|
||||
};
|
||||
/*
|
||||
* Allocate a new instance of the ph7_stream_data structure.
|
||||
@@ -7894,6 +7900,7 @@ static int PHPStreamData_Open(const char *zName, int iMode, ph7_value *pResource
|
||||
/* ph7_int64 (*xRead)(void *,void *,ph7_int64) */
|
||||
static ph7_int64 PHPStreamData_Read(void *pHandle, void *pBuffer, ph7_int64 nDatatoRead) {
|
||||
ph7_stream_data *pData = (ph7_stream_data *)pHandle;
|
||||
ph7_int64 nServed = 0;
|
||||
if(pData == 0) {
|
||||
return -1;
|
||||
}
|
||||
@@ -7901,6 +7908,22 @@ static ph7_int64 PHPStreamData_Read(void *pHandle, void *pBuffer, ph7_int64 nDat
|
||||
/* Forbidden */
|
||||
return -1;
|
||||
}
|
||||
/* Give back bytes that Console::Read() looked ahead but did not consume. */
|
||||
while(pData->nUnread > 0 && nServed < nDatatoRead) {
|
||||
/* Both sides must use the same ring arithmetic (C2): the writer uses
|
||||
* (iUnread + nUnread) % 4, so a bare iUnread++ would read past the
|
||||
* array after four wrap-around cycles. */
|
||||
((unsigned char *)pBuffer)[nServed++] = pData->aUnread[pData->iUnread];
|
||||
pData->iUnread = (pData->iUnread + 1) % SX_ARRAYSIZE(pData->aUnread);
|
||||
if(--pData->nUnread == 0) {
|
||||
pData->iUnread = 0;
|
||||
}
|
||||
}
|
||||
if(nServed >= nDatatoRead) {
|
||||
return nServed;
|
||||
}
|
||||
nDatatoRead -= nServed;
|
||||
pBuffer = (void *)(((unsigned char *)pBuffer) + nServed);
|
||||
#ifdef __WINNT__
|
||||
{
|
||||
DWORD nRd;
|
||||
@@ -7908,9 +7931,9 @@ static ph7_int64 PHPStreamData_Read(void *pHandle, void *pBuffer, ph7_int64 nDat
|
||||
rc = ReadFile(pData->x.pHandle, pBuffer, (DWORD)nDatatoRead, &nRd, 0);
|
||||
if(!rc) {
|
||||
/* IO error */
|
||||
return -1;
|
||||
return nServed > 0 ? nServed : -1;
|
||||
}
|
||||
return (ph7_int64)nRd;
|
||||
return nServed + (ph7_int64)nRd;
|
||||
}
|
||||
#elif defined(__UNIXES__)
|
||||
{
|
||||
@@ -7919,12 +7942,12 @@ static ph7_int64 PHPStreamData_Read(void *pHandle, void *pBuffer, ph7_int64 nDat
|
||||
fd = SX_PTR_TO_INT(pData->x.pHandle);
|
||||
nRd = read(fd, pBuffer, (size_t)nDatatoRead);
|
||||
if(nRd < 1) {
|
||||
return -1;
|
||||
return nServed > 0 ? nServed : -1;
|
||||
}
|
||||
return (ph7_int64)nRd;
|
||||
return nServed + (ph7_int64)nRd;
|
||||
}
|
||||
#else
|
||||
return -1;
|
||||
return nServed > 0 ? nServed : -1;
|
||||
#endif
|
||||
}
|
||||
/* ph7_int64 (*xWrite)(void *,const void *,ph7_int64) */
|
||||
@@ -8160,6 +8183,103 @@ PH7_PRIVATE void *PH7_ExportStdin(ph7_vm *pVm) {
|
||||
return pVm->pStdin;
|
||||
}
|
||||
}
|
||||
/* Give one byte back to the shared stdin stream. When the byte still lives in
|
||||
* io_private's working buffer we simply rewind the offset; otherwise it goes
|
||||
* into php://stdin's low-level pending queue so fgets()/fread() see it next. */
|
||||
PH7_PRIVATE void PH7_StdinUnread(ph7_vm *pVm, unsigned char c) {
|
||||
io_private *pIn = (io_private *)pVm->pStdin;
|
||||
ph7_stream_data *pData;
|
||||
if(pIn == 0 || IO_PRIVATE_INVALID(pIn)) {
|
||||
return;
|
||||
}
|
||||
if(pIn->nOfft > 0 && pIn->nOfft <= SyBlobLength(&pIn->sBuffer)) {
|
||||
pIn->nOfft--;
|
||||
return;
|
||||
}
|
||||
pData = (ph7_stream_data *)pIn->pHandle;
|
||||
if(pData != 0 && pData->iType == PH7_IO_STREAM_STDIN && pData->nUnread < (int)SX_ARRAYSIZE(pData->aUnread)) {
|
||||
pData->aUnread[(pData->iUnread + pData->nUnread) % SX_ARRAYSIZE(pData->aUnread)] = c;
|
||||
pData->nUnread++;
|
||||
}
|
||||
}
|
||||
/* Read one line from the shared stdin handle. StreamReadLine() consults the
|
||||
* same xRead (and therefore the same pending-unread queue) as Console::Read,
|
||||
* fgets() and fread(), so mixing the readers never loses a byte. The returned
|
||||
* buffer is a VM-owned copy: StreamReadLine() may reset its working buffer as
|
||||
* soon as it returns. NULL means EOF without data. */
|
||||
PH7_PRIVATE char *PH7_StdinReadLine(ph7_vm *pVm, int *pLen) {
|
||||
io_private *pIn = (io_private *)PH7_ExportStdin(pVm);
|
||||
const char *zLine;
|
||||
ph7_int64 n;
|
||||
char *pOut;
|
||||
if(pLen == 0) {
|
||||
return 0;
|
||||
}
|
||||
*pLen = 0;
|
||||
if(pIn == 0) {
|
||||
return 0;
|
||||
}
|
||||
n = StreamReadLine(pIn, &zLine, -1);
|
||||
if(n < 1 || n > 0x7FFFFFFF) {
|
||||
return 0;
|
||||
}
|
||||
pOut = (char *)SyMemBackendAlloc(&pVm->sAllocator, (sxu32)(n + 1));
|
||||
if(pOut == 0) {
|
||||
return 0;
|
||||
}
|
||||
SyMemcpy(zLine, pOut, (sxu32)n);
|
||||
pOut[n] = 0;
|
||||
*pLen = (int)n;
|
||||
return pOut;
|
||||
}
|
||||
/* Decode one Unicode code point from the shared stdin stream. Invalid UTF-8
|
||||
* yields 0xFFFD, end of input -1. Bytes inspected but not consumed are
|
||||
* returned with PH7_StdinUnread() so no other reader loses data. Unlike
|
||||
* PH7_Utf8Read(), overlong forms, surrogates and values above U+10FFFF are
|
||||
* rejected here. */
|
||||
PH7_PRIVATE int PH7_StdinReadCodepoint(ph7_vm *pVm) {
|
||||
io_private *pIn = (io_private *)PH7_ExportStdin(pVm);
|
||||
unsigned char c;
|
||||
ph7_int64 n;
|
||||
int i, nWant, nGot = 0, cp, nMin;
|
||||
if(pIn == 0) {
|
||||
return -1;
|
||||
}
|
||||
n = StreamRead(pIn, &c, 1);
|
||||
if(n < 1) {
|
||||
return -1;
|
||||
}
|
||||
if(c < 0x80) {
|
||||
return (int)c;
|
||||
}
|
||||
if(c >= 0xC2 && c <= 0xDF) {
|
||||
nWant = 2; cp = c & 0x1F; nMin = 0x80;
|
||||
} else if(c >= 0xE0 && c <= 0xEF) {
|
||||
nWant = 3; cp = c & 0x0F; nMin = 0x800;
|
||||
} else if(c >= 0xF0 && c <= 0xF4) {
|
||||
nWant = 4; cp = c & 0x07; nMin = 0x10000;
|
||||
} else {
|
||||
return 0xFFFD; /* Continuation byte or invalid lead. */
|
||||
}
|
||||
nGot = 1;
|
||||
for(i = 1 ; i < nWant ; ++i) {
|
||||
n = StreamRead(pIn, &c, 1);
|
||||
if(n < 1) {
|
||||
break; /* Truncated sequence: return replacement for what we got. */
|
||||
}
|
||||
if((c & 0xC0) != 0x80) {
|
||||
PH7_StdinUnread(pVm, c);
|
||||
return 0xFFFD;
|
||||
}
|
||||
cp = (cp << 6) | (c & 0x3F);
|
||||
++nGot;
|
||||
}
|
||||
if(nGot < nWant || cp < nMin || cp > 0x10FFFF ||
|
||||
(cp & 0xFFFFF800) == 0xD800 || (cp & 0xFFFFFFFE) == 0xFFFE) {
|
||||
return 0xFFFD;
|
||||
}
|
||||
return cp;
|
||||
}
|
||||
/*
|
||||
* Export the STDOUT handle.
|
||||
*/
|
||||
|
||||
+218
-421
@@ -2650,6 +2650,7 @@ static ph7_class *VmMethodClass(ph7_vm *pVm) {
|
||||
}
|
||||
return (ph7_class *)pVmFunc->pUserData;
|
||||
}
|
||||
static sxi32 VmImportModule(ph7_vm *, const char *, VmInstr *, int, sxu32);
|
||||
/*
|
||||
* Prepare the Virtual Machine for byte-code execution.
|
||||
* This routine gets called by the PH7 engine after
|
||||
@@ -2705,6 +2706,22 @@ PH7_PRIVATE sxi32 PH7_VmMakeReady(
|
||||
PH7_RegisterBuiltInConstant(&(*pVm));
|
||||
/* Register built-in functions [i.e: array_diff(), strlen(), etc.] */
|
||||
PH7_RegisterBuiltInFunction(&(*pVm));
|
||||
/* Load imported modules BEFORE evaluating class initializers: a static or
|
||||
* constant field may reference a class published by initializeModule().
|
||||
* Native classes are mounted once after every init() has run (two-phase). */
|
||||
{
|
||||
VmInstr *aInstr = (VmInstr *)SySetBasePtr(pVm->pByteContainer);
|
||||
sxu32 nInstr = SySetUsed(pVm->pByteContainer), i;
|
||||
sxu32 nPreexisting = SySetUsed(&pVm->aModules);
|
||||
for(i = 0 ; i < nInstr ; ++i) {
|
||||
if(aInstr[i].iOp == PH7_OP_IMPORT) {
|
||||
rc = VmImportModule(pVm, (const char *)aInstr[i].p3, &aInstr[i], TRUE, nPreexisting);
|
||||
if(rc != SXRET_OK) {
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Initialize and install static and constants class attributes */
|
||||
SyHashResetLoopCursor(&pVm->hClass);
|
||||
while((pEntry = SyHashGetNextEntry(&pVm->hClass)) != 0) {
|
||||
@@ -2873,6 +2890,19 @@ PH7_PRIVATE sxi32 PH7_VmRelease(ph7_vm *pVm) {
|
||||
while(SySetGetNextEntry(&pVm->aMemObj, (void **)&pObj) == SXRET_OK) {
|
||||
PH7_MemObjRelease(pObj);
|
||||
}
|
||||
/* Release per-module state exactly once (C13), BEFORE dlclose() makes the
|
||||
* module's release callback unreachable. aModuleHandles holds snapshots
|
||||
* taken at load time, before any state was published, so only the live
|
||||
* aModules entries carry a release callback. */
|
||||
SySetResetCursor(&pVm->aModules);
|
||||
while(SySetGetNextEntry(&pVm->aModules, (void **)&pEntry) == SXRET_OK) {
|
||||
VmModule *pModule = (VmModule *)pEntry;
|
||||
if(pModule->pUserData && pModule->xRelease) {
|
||||
pModule->xRelease(pModule->pUserData);
|
||||
}
|
||||
pModule->pUserData = 0;
|
||||
pModule->xRelease = 0;
|
||||
}
|
||||
/* Iterate through modules list */
|
||||
while(SySetGetNextEntry(&pVm->aModuleHandles, (void **)&pEntry) == SXRET_OK) {
|
||||
/* Unload the module */
|
||||
@@ -3780,17 +3810,175 @@ PH7_PRIVATE sxi32 PH7_VmThrowError(
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
/* Exact module-name lookup; do not disturb the set's iteration cursor. */
|
||||
static sxi32 VmModuleLoaded(ph7_vm *pVm, const char *zName, sxu32 nLen) {
|
||||
/* Exact module-name lookup; do not disturb the set's iteration cursor.
|
||||
* Returns the 1-based slot so callers can tell modules loaded by an earlier
|
||||
* compilation (ph7_vm_reset keeps aModules) from duplicates in this one. */
|
||||
static sxu32 VmModuleSlot(ph7_vm *pVm, const char *zName, sxu32 nLen) {
|
||||
sxu32 i;
|
||||
VmModule *pModule;
|
||||
for(i = 0; i < SySetUsed(&pVm->aModules); ++i) {
|
||||
pModule = (VmModule *)SySetAt(&pVm->aModules, i);
|
||||
if(pModule->sName.nByte == nLen && SyStrncmp(pModule->sName.zString, zName, nLen) == 0) {
|
||||
return TRUE;
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
return 0;
|
||||
}
|
||||
static sxi32 VmModuleLoaded(ph7_vm *pVm, const char *zName, sxu32 nLen) {
|
||||
return VmModuleSlot(pVm, zName, nLen) ? TRUE : FALSE;
|
||||
}
|
||||
/* Per-VM, per-module opaque state published by the module itself (C13).
|
||||
* aModules is kept across ph7_vm_reset(), so the data survives a reset too;
|
||||
* the module re-initializes from PH7_VM_CONFIG on the next import attempt
|
||||
* only when it chooses to. PH7_VmModuleData() returns NULL for an unknown
|
||||
* module; PH7_VmSetModuleData() returns SXERR_NOTFOUND (never PH7_NOMEM,
|
||||
* which is reserved for allocation failures). */
|
||||
PH7_PRIVATE void *PH7_VmModuleData(ph7_vm *pVm, const char *zModule) {
|
||||
sxu32 nSlot;
|
||||
if(pVm == 0 || zModule == 0) {
|
||||
return 0;
|
||||
}
|
||||
nSlot = VmModuleSlot(pVm, zModule, (sxu32)SyStrlen(zModule));
|
||||
return nSlot ? ((VmModule *)SySetAt(&pVm->aModules, nSlot - 1))->pUserData : 0;
|
||||
}
|
||||
PH7_PRIVATE sxi32 PH7_VmSetModuleData(ph7_vm *pVm, const char *zModule,
|
||||
void *pData, void (*xRelease)(void *)) {
|
||||
VmModule *pModule;
|
||||
sxu32 nSlot;
|
||||
if(pVm == 0 || zModule == 0 || (nSlot = VmModuleSlot(pVm, zModule, (sxu32)SyStrlen(zModule))) == 0) {
|
||||
return SXERR_NOTFOUND;
|
||||
}
|
||||
pModule = (VmModule *)SySetAt(&pVm->aModules, nSlot - 1);
|
||||
/* Replacing existing state releases the old value exactly once. */
|
||||
if(pModule->pUserData && pModule->pUserData != pData && pModule->xRelease) {
|
||||
pModule->xRelease(pModule->pUserData);
|
||||
}
|
||||
pModule->pUserData = pData;
|
||||
pModule->xRelease = xRelease;
|
||||
return SXRET_OK;
|
||||
}
|
||||
/* Import instruction status (VmInstr.iP1): pre-scan marks every import so the
|
||||
* runtime handler only has to replay diagnostics, never load code twice. */
|
||||
#define VM_IMPORT_PENDING 0
|
||||
#define VM_IMPORT_PRELOADED 1
|
||||
#define VM_IMPORT_FAILED 2
|
||||
#define VM_IMPORT_DUPLICATE 3
|
||||
/* Failure reasons (VmInstr.iP2) replayed by the runtime handler. */
|
||||
#define VM_IMPORT_FAIL_PATH 1
|
||||
#define VM_IMPORT_FAIL_MEMORY 2
|
||||
#define VM_IMPORT_FAIL_MISSING 3
|
||||
#define VM_IMPORT_FAIL_NOINIT 4
|
||||
#define VM_IMPORT_FAIL_INIT 5
|
||||
#define VM_IMPORT_FAIL_REGISTER 6
|
||||
/* Set at the first runtime execution of a pre-loaded import. A second
|
||||
* execution of the same bytecode after ph7_vm_reset() sees the module still
|
||||
* registered in aModules and reports "already loaded". */
|
||||
#define VM_IMPORT_REPLAYED 7
|
||||
/* Do the actual dlopen()/initializeModule() work. Warnings are suppressed in
|
||||
* the pre-scan (there is no script frame yet, so they would point at
|
||||
* [MEMORY]:1); the instruction instead records what the runtime must report. */
|
||||
static sxi32 VmImportModule(ph7_vm *pVm, const char *zModule, VmInstr *pInstr,
|
||||
int bPreScan, sxu32 nPreexisting) {
|
||||
VmModule pModule;
|
||||
char bfile[255];
|
||||
char *zFile;
|
||||
int nFile;
|
||||
sxu32 nSize, nSlot;
|
||||
sxi32 (*init)(ph7_vm *, ph7_real *, SyString *);
|
||||
int nLen = SyStrlen(zModule);
|
||||
if(nLen < 1) {
|
||||
return SXRET_OK;
|
||||
}
|
||||
nSlot = VmModuleSlot(pVm, zModule, (sxu32)nLen);
|
||||
if(nSlot > 0) {
|
||||
/* A module left in aModules by an earlier compilation (ph7_vm_reset
|
||||
* keeps it: dropping it would orphan published functions/classes)
|
||||
* must still replay the "already loaded" warning at run time, so
|
||||
* leave the instruction pending. A duplicate within this bytecode
|
||||
* is reported immediately. */
|
||||
pInstr->iP1 = (bPreScan && nSlot <= nPreexisting) ? VM_IMPORT_PENDING : VM_IMPORT_DUPLICATE;
|
||||
return SXRET_OK;
|
||||
}
|
||||
SyZero(&pModule, sizeof(VmModule));
|
||||
SyStringInitFromBuf(&pModule.sName, zModule, nLen);
|
||||
nFile = snprintf(bfile, sizeof(bfile), "./binary/%s%s", zModule, PH7_LIBRARY_SUFFIX);
|
||||
if(nFile < 0 || nFile >= (int)sizeof(bfile)) {
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_PATH;
|
||||
return SXRET_OK;
|
||||
}
|
||||
zFile = SyMemBackendStrDup(&pVm->sAllocator, bfile, (sxu32)nFile);
|
||||
if(zFile == 0) {
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_MEMORY;
|
||||
return SXRET_OK;
|
||||
}
|
||||
SyStringInitFromBuf(&pModule.sFile, zFile, nFile);
|
||||
#ifdef __WINNT__
|
||||
pModule.pHandle = LoadLibrary(zFile);
|
||||
#else
|
||||
pModule.pHandle = dlopen(pModule.sFile.zString, RTLD_LAZY);
|
||||
#endif
|
||||
if(!pModule.pHandle) {
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_MISSING;
|
||||
SyMemBackendFree(&pVm->sAllocator, zFile);
|
||||
return SXRET_OK;
|
||||
}
|
||||
#ifdef __WINNT__
|
||||
*(void**)(&init) = GetProcAddress(pModule.pHandle, "initializeModule");
|
||||
#else
|
||||
*(void**)(&init) = dlsym(pModule.pHandle, "initializeModule");
|
||||
#endif
|
||||
nSize = pVm->aModuleHandles.nSize;
|
||||
if(!init || SySetPut(&pVm->aModuleHandles, &pModule) != SXRET_OK) {
|
||||
pVm->aModuleHandles.nSize = nSize;
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_NOINIT;
|
||||
#ifdef __WINNT__
|
||||
FreeLibrary(pModule.pHandle);
|
||||
#else
|
||||
dlclose(pModule.pHandle);
|
||||
#endif
|
||||
SyMemBackendFree(&pVm->sAllocator, zFile);
|
||||
return SXRET_OK;
|
||||
}
|
||||
/* Init may publish callbacks even on failure. Retain its handle until VM
|
||||
* release, but only successful imports enter the lookup registry. */
|
||||
if(init(pVm, &pModule.fVer, &pModule.sDesc) != SXRET_OK) {
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_INIT;
|
||||
} else {
|
||||
nSize = pVm->aModules.nSize;
|
||||
if(SySetPut(&pVm->aModules, &pModule) != SXRET_OK) {
|
||||
pVm->aModules.nSize = nSize;
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_REGISTER;
|
||||
} else {
|
||||
pInstr->iP1 = VM_IMPORT_PRELOADED;
|
||||
}
|
||||
}
|
||||
/* Native classes introduced by init() are mounted once, after every
|
||||
* module has been initialized (see PH7_VmMakeReady). */
|
||||
SXUNUSED(bPreScan);
|
||||
return SXRET_OK;
|
||||
}
|
||||
/* Replay an import diagnostic now that a script frame is active. */
|
||||
static void VmImportReport(ph7_vm *pVm, const char *zModule, VmInstr *pInstr) {
|
||||
switch(pInstr->iP2) {
|
||||
case VM_IMPORT_FAIL_PATH:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Module path too long for '%s'", zModule);
|
||||
break;
|
||||
case VM_IMPORT_FAIL_MEMORY:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Out of memory loading '%s'", zModule);
|
||||
break;
|
||||
case VM_IMPORT_FAIL_MISSING:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: No module named '%s' found", zModule);
|
||||
break;
|
||||
case VM_IMPORT_FAIL_NOINIT:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Cannot initialize module '%s'", zModule);
|
||||
break;
|
||||
case VM_IMPORT_FAIL_INIT:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Initialization of module '%s' failed", zModule);
|
||||
break;
|
||||
case VM_IMPORT_FAIL_REGISTER:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Cannot register module '%s'", zModule);
|
||||
break;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Execute as much of a PH7 bytecode program as we can then return.
|
||||
@@ -6034,77 +6222,39 @@ Resume:
|
||||
*/
|
||||
case PH7_OP_IMPORT:
|
||||
{
|
||||
VmModule pModule;
|
||||
char bfile[255];
|
||||
char *zFile;
|
||||
int nFile;
|
||||
sxu32 nSize;
|
||||
sxi32 (*init)(ph7_vm *, ph7_real *, SyString *);
|
||||
char *zModule = (char *) pInstr->p3;
|
||||
int nLen = SyStrlen(zModule);
|
||||
if(nLen < 1) {
|
||||
if(pInstr->iP1 == VM_IMPORT_PRELOADED) {
|
||||
/* Loaded before user-class initializers ran: no work
|
||||
* and no warning on the first execution. A second
|
||||
* execution of the same bytecode after ph7_vm_reset
|
||||
* observes the still-registered module as a duplicate. */
|
||||
if(pInstr->iP2 == VM_IMPORT_REPLAYED) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING,
|
||||
"ImportError: Module '%s' already loaded", zModule);
|
||||
} else {
|
||||
pInstr->iP2 = VM_IMPORT_REPLAYED;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if(VmModuleLoaded(pVm, zModule, (sxu32)nLen)) {
|
||||
if(pInstr->iP1 == VM_IMPORT_FAILED) {
|
||||
VmImportReport(pVm, zModule, pInstr);
|
||||
break;
|
||||
}
|
||||
if(pInstr->iP1 == VM_IMPORT_DUPLICATE) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Module '%s' already loaded", zModule);
|
||||
break;
|
||||
}
|
||||
|
||||
/* Zero the module entry */
|
||||
SyZero(&pModule, sizeof(VmModule));
|
||||
SyStringInitFromBuf(&pModule.sName, zModule, nLen);
|
||||
nFile = snprintf(bfile, sizeof(bfile), "./binary/%s%s", zModule, PH7_LIBRARY_SUFFIX);
|
||||
if(nFile < 0 || nFile >= (int)sizeof(bfile)) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Module path too long for '%s'", zModule);
|
||||
break;
|
||||
}
|
||||
zFile = SyMemBackendStrDup(&pVm->sAllocator, bfile, (sxu32)nFile);
|
||||
if(zFile == 0) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Out of memory loading '%s'", zModule);
|
||||
break;
|
||||
}
|
||||
SyStringInitFromBuf(&pModule.sFile, zFile, nFile);
|
||||
#ifdef __WINNT__
|
||||
pModule.pHandle = LoadLibrary(zFile);
|
||||
#else
|
||||
pModule.pHandle = dlopen(pModule.sFile.zString, RTLD_LAZY);
|
||||
#endif
|
||||
if(!pModule.pHandle) {
|
||||
/* Could not load the module library file */
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: No module named '%z' found", &pModule.sName);
|
||||
SyMemBackendFree(&pVm->sAllocator, zFile);
|
||||
break;
|
||||
}
|
||||
#ifdef __WINNT__
|
||||
*(void**)(&init) = GetProcAddress(pModule.pHandle, "initializeModule");
|
||||
#else
|
||||
*(void**)(&init) = dlsym(pModule.pHandle, "initializeModule");
|
||||
#endif
|
||||
nSize = pVm->aModuleHandles.nSize;
|
||||
if(!init || SySetPut(&pVm->aModuleHandles, &pModule) != SXRET_OK) {
|
||||
/* SySetPut may change capacity before allocation fails. */
|
||||
pVm->aModuleHandles.nSize = nSize;
|
||||
/* No callbacks have been published yet; unloading is safe. */
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Cannot initialize module '%z'", &pModule.sName);
|
||||
#ifdef __WINNT__
|
||||
FreeLibrary(pModule.pHandle);
|
||||
#else
|
||||
dlclose(pModule.pHandle);
|
||||
#endif
|
||||
SyMemBackendFree(&pVm->sAllocator, zFile);
|
||||
break;
|
||||
}
|
||||
/* Init may publish callbacks even on failure. Retain its handle until
|
||||
* VM release, but only successful imports enter the lookup registry. */
|
||||
if(init(pVm, &pModule.fVer, &pModule.sDesc) != SXRET_OK) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Initialization of module '%z' failed", &pModule.sName);
|
||||
} else {
|
||||
nSize = pVm->aModules.nSize;
|
||||
if(SySetPut(&pVm->aModules, &pModule) != SXRET_OK) {
|
||||
/* Keep the lookup registry retryable after allocation failure. */
|
||||
pVm->aModules.nSize = nSize;
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Cannot register module '%z'", &pModule.sName);
|
||||
rc = VmImportModule(pVm, zModule, pInstr, FALSE, 0);
|
||||
if(rc != SXRET_OK) {
|
||||
if(rc == SXERR_MEM) {
|
||||
PH7_VmMemoryError(pVm);
|
||||
}
|
||||
goto Abort;
|
||||
}
|
||||
if(pInstr->iP1 == VM_IMPORT_FAILED) {
|
||||
VmImportReport(pVm, zModule, pInstr);
|
||||
} else if(pInstr->iP1 == VM_IMPORT_DUPLICATE) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Module '%s' already loaded", zModule);
|
||||
}
|
||||
rc = VmMountNativeClasses(pVm);
|
||||
if(rc == SXERR_MEM) {
|
||||
@@ -9814,38 +9964,6 @@ static int vm_builtin_uniqid(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
* Status:
|
||||
* Stable.
|
||||
*/
|
||||
/*
|
||||
* int print($string...)
|
||||
* Output one or more messages.
|
||||
* Parameters
|
||||
* $string
|
||||
* Message to output.
|
||||
* Return
|
||||
* NULL.
|
||||
*/
|
||||
static int vm_builtin_print(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
const char *zData;
|
||||
int nDataLen = 0;
|
||||
ph7_vm *pVm;
|
||||
int i, rc;
|
||||
/* Point to the target VM */
|
||||
pVm = pCtx->pVm;
|
||||
/* Output */
|
||||
for(i = 0 ; i < nArg ; ++i) {
|
||||
zData = ph7_value_to_string(apArg[i], &nDataLen);
|
||||
if(pVm->iPendingTransfer) {
|
||||
return pVm->iPendingTransfer;
|
||||
}
|
||||
if(nDataLen > 0) {
|
||||
rc = pVm->sVmConsumer.xConsumer((const void *)zData, (unsigned int)nDataLen, pVm->sVmConsumer.pUserData);
|
||||
if(rc == SXERR_ABORT) {
|
||||
/* Output consumer callback request an operation abort */
|
||||
return PH7_ABORT;
|
||||
}
|
||||
}
|
||||
}
|
||||
return SXRET_OK;
|
||||
}
|
||||
/*
|
||||
* void exit(string $msg)
|
||||
* void exit(int $status)
|
||||
@@ -11761,325 +11879,6 @@ static int vm_builtin_get_included_files(ph7_context *pCtx, int nArg, ph7_value
|
||||
*/
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* Section:
|
||||
* Command line arguments processing.
|
||||
* Authors:
|
||||
* Symisc Systems,devel@symisc.net.
|
||||
* Copyright (C) Symisc Systems,https://ph7.symisc.net
|
||||
* Status:
|
||||
* Stable.
|
||||
*/
|
||||
/*
|
||||
* Check if a short option argument [i.e: -c] is available in the command
|
||||
* line string. Return a pointer to the start of the stream on success.
|
||||
* NULL otherwise.
|
||||
*/
|
||||
static const char *VmFindShortOpt(int c, const char *zIn, const char *zEnd) {
|
||||
while(zIn < zEnd) {
|
||||
if(zIn[0] == '-' && &zIn[1] < zEnd && (int)zIn[1] == c) {
|
||||
/* Got one */
|
||||
return &zIn[1];
|
||||
}
|
||||
/* Advance the cursor */
|
||||
zIn++;
|
||||
}
|
||||
/* No such option */
|
||||
return 0;
|
||||
}
|
||||
/*
|
||||
* Check if a long option argument [i.e: --opt] is available in the command
|
||||
* line string. Return a pointer to the start of the stream on success.
|
||||
* NULL otherwise.
|
||||
*/
|
||||
static const char *VmFindLongOpt(const char *zLong, int nByte, const char *zIn, const char *zEnd) {
|
||||
const char *zOpt;
|
||||
while(zIn < zEnd) {
|
||||
if(zIn[0] == '-' && &zIn[1] < zEnd && (int)zIn[1] == '-') {
|
||||
zIn += 2;
|
||||
zOpt = zIn;
|
||||
while(zIn < zEnd && !SyisSpace(zIn[0])) {
|
||||
if(zIn[0] == '=' /* --opt=val */) {
|
||||
break;
|
||||
}
|
||||
zIn++;
|
||||
}
|
||||
/* Test */
|
||||
if((int)(zIn - zOpt) == nByte && SyMemcmp(zOpt, zLong, nByte) == 0) {
|
||||
/* Got one, return it's value */
|
||||
return zIn;
|
||||
}
|
||||
} else {
|
||||
zIn++;
|
||||
}
|
||||
}
|
||||
/* No such option */
|
||||
return 0;
|
||||
}
|
||||
/*
|
||||
* Long option [i.e: --opt] arguments private data structure.
|
||||
*/
|
||||
struct getopt_long_opt {
|
||||
const char *zArgIn, *zArgEnd; /* Command line arguments */
|
||||
ph7_value *pWorker; /* Worker variable*/
|
||||
ph7_value *pArray; /* getopt() return value */
|
||||
ph7_context *pCtx; /* Call Context */
|
||||
};
|
||||
/* Forward declaration */
|
||||
static int VmProcessLongOpt(ph7_value *pKey, ph7_value *pValue, void *pUserData);
|
||||
/*
|
||||
* Extract short or long argument option values.
|
||||
*/
|
||||
static void VmExtractOptArgValue(
|
||||
ph7_value *pArray, /* getopt() return value */
|
||||
ph7_value *pWorker, /* Worker variable */
|
||||
const char *zArg, /* Argument stream */
|
||||
const char *zArgEnd,/* End of the argument stream */
|
||||
int need_val, /* TRUE to fetch option argument */
|
||||
ph7_context *pCtx, /* Call Context */
|
||||
const char *zName /* Option name */) {
|
||||
ph7_value_bool(pWorker, 0);
|
||||
if(!need_val) {
|
||||
/*
|
||||
* Option does not need arguments.
|
||||
* Insert the option name and a boolean FALSE.
|
||||
*/
|
||||
ph7_array_add_strkey_elem(pArray, (const char *)zName, pWorker); /* Will make it's own copy */
|
||||
} else {
|
||||
const char *zCur;
|
||||
/* Extract option argument */
|
||||
zArg++;
|
||||
if(zArg < zArgEnd && zArg[0] == '=') {
|
||||
zArg++;
|
||||
}
|
||||
while(zArg < zArgEnd && (unsigned char)zArg[0] < 0xc0 && SyisSpace(zArg[0])) {
|
||||
zArg++;
|
||||
}
|
||||
if(zArg >= zArgEnd || zArg[0] == '-') {
|
||||
/*
|
||||
* Argument not found.
|
||||
* Insert the option name and a boolean FALSE.
|
||||
*/
|
||||
ph7_array_add_strkey_elem(pArray, (const char *)zName, pWorker); /* Will make it's own copy */
|
||||
return;
|
||||
}
|
||||
/* Delimit the value */
|
||||
zCur = zArg;
|
||||
if(zArg[0] == '\'' || zArg[0] == '"') {
|
||||
int d = zArg[0];
|
||||
/* Delimit the argument */
|
||||
zArg++;
|
||||
zCur = zArg;
|
||||
while(zArg < zArgEnd) {
|
||||
if(zArg[0] == d && zArg[-1] != '\\') {
|
||||
/* Delimiter found,exit the loop */
|
||||
break;
|
||||
}
|
||||
zArg++;
|
||||
}
|
||||
/* Save the value */
|
||||
ph7_value_string(pWorker, zCur, (int)(zArg - zCur));
|
||||
if(zArg < zArgEnd) {
|
||||
zArg++;
|
||||
}
|
||||
} else {
|
||||
while(zArg < zArgEnd && !SyisSpace(zArg[0])) {
|
||||
zArg++;
|
||||
}
|
||||
/* Save the value */
|
||||
ph7_value_string(pWorker, zCur, (int)(zArg - zCur));
|
||||
}
|
||||
/*
|
||||
* Check if we are dealing with multiple values.
|
||||
* If so,create an array to hold them,rather than a scalar variable.
|
||||
*/
|
||||
while(zArg < zArgEnd && (unsigned char)zArg[0] < 0xc0 && SyisSpace(zArg[0])) {
|
||||
zArg++;
|
||||
}
|
||||
if(zArg < zArgEnd && zArg[0] != '-') {
|
||||
ph7_value *pOptArg; /* Array of option arguments */
|
||||
pOptArg = ph7_context_new_array(pCtx);
|
||||
if(pOptArg == 0) {
|
||||
PH7_VmMemoryError(pCtx->pVm);
|
||||
} else {
|
||||
/* Insert the first value */
|
||||
ph7_array_add_elem(pOptArg, 0, pWorker); /* Will make it's own copy */
|
||||
for(;;) {
|
||||
if(zArg >= zArgEnd || zArg[0] == '-') {
|
||||
/* No more value */
|
||||
break;
|
||||
}
|
||||
/* Delimit the value */
|
||||
zCur = zArg;
|
||||
if(zArg < zArgEnd && zArg[0] == '\\') {
|
||||
zArg++;
|
||||
zCur = zArg;
|
||||
}
|
||||
while(zArg < zArgEnd && !SyisSpace(zArg[0])) {
|
||||
zArg++;
|
||||
}
|
||||
/* Reset the string cursor */
|
||||
ph7_value_reset_string_cursor(pWorker);
|
||||
/* Save the value */
|
||||
ph7_value_string(pWorker, zCur, (int)(zArg - zCur));
|
||||
/* Insert */
|
||||
ph7_array_add_elem(pOptArg, 0, pWorker); /* Will make it's own copy */
|
||||
/* Jump trailing white spaces */
|
||||
while(zArg < zArgEnd && (unsigned char)zArg[0] < 0xc0 && SyisSpace(zArg[0])) {
|
||||
zArg++;
|
||||
}
|
||||
}
|
||||
/* Insert the option arg array */
|
||||
ph7_array_add_strkey_elem(pArray, (const char *)zName, pOptArg); /* Will make it's own copy */
|
||||
/* Safely release */
|
||||
ph7_context_release_value(pCtx, pOptArg);
|
||||
}
|
||||
} else {
|
||||
/* Single value */
|
||||
ph7_array_add_strkey_elem(pArray, (const char *)zName, pWorker); /* Will make it's own copy */
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* array getopt(string $options[,array $longopts ])
|
||||
* Gets options from the command line argument list.
|
||||
* Parameters
|
||||
* $options
|
||||
* Each character in this string will be used as option characters
|
||||
* and matched against options passed to the script starting with
|
||||
* a single hyphen (-). For example, an option string "x" recognizes
|
||||
* an option -x. Only a-z, A-Z and 0-9 are allowed.
|
||||
* $longopts
|
||||
* An array of options. Each element in this array will be used as option
|
||||
* strings and matched against options passed to the script starting with
|
||||
* two hyphens (--). For example, an longopts element "opt" recognizes an
|
||||
* option --opt.
|
||||
* Return
|
||||
* This function will return an array of option / argument pairs or FALSE
|
||||
* on failure.
|
||||
*/
|
||||
static int vm_builtin_getopt(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
const char *zIn, *zEnd, *zArg, *zArgIn, *zArgEnd;
|
||||
struct getopt_long_opt sLong;
|
||||
ph7_value *pArray, *pWorker;
|
||||
SyBlob *pArg;
|
||||
int nByte;
|
||||
if(nArg < 1 || !ph7_value_is_string(apArg[0])) {
|
||||
/* Missing/Invalid arguments, return FALSE */
|
||||
PH7_VmThrowError(pCtx->pVm, PH7_CTX_ERR, "Missing/Invalid option arguments");
|
||||
}
|
||||
/* Extract option arguments */
|
||||
zIn = ph7_value_to_string(apArg[0], &nByte);
|
||||
zEnd = &zIn[nByte];
|
||||
/* Point to the string representation of the $argv[] array */
|
||||
pArg = &pCtx->pVm->sArgv;
|
||||
/* Create a new empty array and a worker variable */
|
||||
pArray = ph7_context_new_array(pCtx);
|
||||
pWorker = ph7_context_new_scalar(pCtx);
|
||||
if(pArray == 0 || pWorker == 0) {
|
||||
PH7_VmMemoryError(pCtx->pVm);
|
||||
}
|
||||
if(SyBlobLength(pArg) < 1) {
|
||||
/* Empty command line, return the empty array*/
|
||||
ph7_result_value(pCtx, pArray);
|
||||
/* Everything will be released automatically when we return
|
||||
* from this function.
|
||||
*/
|
||||
return PH7_OK;
|
||||
}
|
||||
zArgIn = (const char *)SyBlobData(pArg);
|
||||
zArgEnd = &zArgIn[SyBlobLength(pArg)];
|
||||
/* Fill the long option structure */
|
||||
sLong.pArray = pArray;
|
||||
sLong.pWorker = pWorker;
|
||||
sLong.zArgIn = zArgIn;
|
||||
sLong.zArgEnd = zArgEnd;
|
||||
sLong.pCtx = pCtx;
|
||||
/* Start processing */
|
||||
while(zIn < zEnd) {
|
||||
int c = zIn[0];
|
||||
int need_val = 0;
|
||||
/* Advance the stream cursor */
|
||||
zIn++;
|
||||
/* Ignore non-alphanum characters */
|
||||
if(!SyisAlphaNum(c)) {
|
||||
continue;
|
||||
}
|
||||
if(zIn < zEnd && zIn[0] == ':') {
|
||||
zIn++;
|
||||
need_val = 1;
|
||||
if(zIn < zEnd && zIn[0] == ':') {
|
||||
zIn++;
|
||||
}
|
||||
}
|
||||
/* Find option */
|
||||
zArg = VmFindShortOpt(c, zArgIn, zArgEnd);
|
||||
if(zArg == 0) {
|
||||
/* No such option */
|
||||
continue;
|
||||
}
|
||||
/* Extract option argument value */
|
||||
VmExtractOptArgValue(pArray, pWorker, zArg, zArgEnd, need_val, pCtx, (const char *)&c);
|
||||
}
|
||||
if(nArg > 1 && ph7_value_is_array(apArg[1]) && ph7_array_count(apArg[1]) > 0) {
|
||||
/* Process long options */
|
||||
ph7_array_walk(apArg[1], VmProcessLongOpt, &sLong);
|
||||
}
|
||||
/* Return the option array */
|
||||
ph7_result_value(pCtx, pArray);
|
||||
/*
|
||||
* Don't worry about freeing memory, everything will be released
|
||||
* automatically as soon we return from this foreign function.
|
||||
*/
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* Array walker callback used for processing long options values.
|
||||
*/
|
||||
static int VmProcessLongOpt(ph7_value *pKey, ph7_value *pValue, void *pUserData) {
|
||||
struct getopt_long_opt *pOpt = (struct getopt_long_opt *)pUserData;
|
||||
const char *zArg, *zOpt, *zEnd;
|
||||
int need_value = 0;
|
||||
int nByte;
|
||||
/* Value must be of type string */
|
||||
if(!ph7_value_is_string(pValue)) {
|
||||
/* Simply ignore */
|
||||
return PH7_OK;
|
||||
}
|
||||
zOpt = ph7_value_to_string(pValue, &nByte);
|
||||
if(nByte < 1) {
|
||||
/* Empty string,ignore */
|
||||
return PH7_OK;
|
||||
}
|
||||
zEnd = &zOpt[nByte - 1];
|
||||
if(zEnd[0] == ':') {
|
||||
char *zTerm;
|
||||
/* Try to extract a value */
|
||||
need_value = 1;
|
||||
while(zEnd >= zOpt && zEnd[0] == ':') {
|
||||
zEnd--;
|
||||
}
|
||||
if(zOpt >= zEnd) {
|
||||
/* Empty string,ignore */
|
||||
SXUNUSED(pKey);
|
||||
return PH7_OK;
|
||||
}
|
||||
zEnd++;
|
||||
zTerm = (char *)zEnd;
|
||||
zTerm[0] = 0;
|
||||
} else {
|
||||
zEnd = &zOpt[nByte];
|
||||
}
|
||||
/* Find the option */
|
||||
zArg = VmFindLongOpt(zOpt, (int)(zEnd - zOpt), pOpt->zArgIn, pOpt->zArgEnd);
|
||||
if(zArg == 0) {
|
||||
/* No such option, return immediately */
|
||||
return PH7_OK;
|
||||
}
|
||||
/* Try to extract a value */
|
||||
VmExtractOptArgValue(pOpt->pArray, pOpt->pWorker, zArg, pOpt->zArgEnd, need_value, pOpt->pCtx, zOpt);
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* int utf8_encode(string $input)
|
||||
* UTF-8 encoding.
|
||||
@@ -12289,7 +12088,6 @@ static const ph7_builtin_func aVmFunc[] = {
|
||||
{ "random_bytes", vm_builtin_random_bytes },
|
||||
{ "uniqid", vm_builtin_uniqid },
|
||||
/* Language constructs functions */
|
||||
{ "print", vm_builtin_print },
|
||||
{ "exit", vm_builtin_exit },
|
||||
{ "eval", vm_builtin_eval },
|
||||
/* Variable handling functions */
|
||||
@@ -12338,7 +12136,6 @@ static const ph7_builtin_func aVmFunc[] = {
|
||||
{"utf8_encode", vm_builtin_utf8_encode},
|
||||
{"utf8_decode", vm_builtin_utf8_decode},
|
||||
/* Command line processing */
|
||||
{"getopt", vm_builtin_getopt },
|
||||
/* Files/URI inclusion facility */
|
||||
{ "get_include_path", vm_builtin_get_include_path },
|
||||
{ "get_included_files", vm_builtin_get_included_files},
|
||||
|
||||
@@ -1389,6 +1389,11 @@ struct VmModule {
|
||||
SyString sFile; /* Module library file */
|
||||
SyString sDesc; /* Module short description */
|
||||
ph7_real fVer; /* Module version */
|
||||
/* Per-VM module state published by the module itself (C13). aModules
|
||||
* survives ph7_vm_reset(), so this data does too; xRelease runs exactly
|
||||
* once when the VM is released or when the data is overwritten. */
|
||||
void *pUserData; /* Module-owned state, NULL when unused */
|
||||
void (*xRelease)(void *); /* Release callback for pUserData */
|
||||
};
|
||||
/*
|
||||
* Each installed class autoload callback (registered using [register_autoload_handler()] )
|
||||
@@ -1788,6 +1793,13 @@ PH7_PRIVATE sxi32 PH7_VmOutputConsume(ph7_vm *pVm, SyString *pString);
|
||||
PH7_PRIVATE sxi32 PH7_VmOutputConsumeAp(ph7_vm *pVm, const char *zFormat, va_list ap);
|
||||
PH7_PRIVATE sxi32 PH7_VmMemoryError(ph7_vm *pVm);
|
||||
PH7_PRIVATE sxi32 PH7_VmThrowError(ph7_vm *pVm, sxi32 iErr, const char *zMessage, ...);
|
||||
/* classes.c: publish a core IOException instance as a pending exception.
|
||||
* Returns PH7_EXCEPTION on success, PH7_ABORT on allocation failure. */
|
||||
PH7_PRIVATE sxi32 PH7_VmThrowIoException(ph7_context *pCtx, int nCode, const char *zMsg);
|
||||
/* vm.c: per-VM, per-module opaque state (C13). Lookups are by module name. */
|
||||
PH7_PRIVATE void *PH7_VmModuleData(ph7_vm *pVm, const char *zModule);
|
||||
PH7_PRIVATE sxi32 PH7_VmSetModuleData(ph7_vm *pVm, const char *zModule,
|
||||
void *pData, void (*xRelease)(void *));
|
||||
PH7_PRIVATE void PH7_VmExpandConstantValue(ph7_value *pVal, void *pUserData);
|
||||
PH7_PRIVATE sxi32 VmExtractDebugTrace(ph7_vm *pVm, SySet *pDebugTrace);
|
||||
PH7_PRIVATE sxi32 PH7_VmDump(ph7_vm *pVm, ProcConsumer xConsumer, void *pUserData);
|
||||
@@ -1876,6 +1888,24 @@ PH7_PRIVATE sxi32 PH7_ProcessCsv(const char *zInput, int nByte, int delim, int e
|
||||
PH7_PRIVATE sxi32 PH7_CsvConsumer(const char *zToken, int nTokenLen, void *pUserData);
|
||||
PH7_PRIVATE sxi32 PH7_StripTagsFromString(ph7_context *pCtx, const char *zIn, int nByte, const char *zTaglist, int nTaglen);
|
||||
PH7_PRIVATE sxi32 PH7_ParseIniString(ph7_context *pCtx, const char *zIn, sxu32 nByte, int bProcessSection);
|
||||
/* textwriter.c — TextWriter C API. A writer backend owns three callbacks:
|
||||
* xWrite emits one already-formatted chunk, xFlush flushes it and xRelease
|
||||
* frees the backend exactly once, from a TextWriter instance destructor. */
|
||||
typedef struct ph7_text_writer_methods {
|
||||
int (*xWrite)(void *, const void *, unsigned int);
|
||||
int (*xFlush)(void *);
|
||||
void (*xRelease)(void *);
|
||||
} ph7_text_writer_methods;
|
||||
PH7_PRIVATE int ph7_text_writer_new(ph7_context *, const ph7_text_writer_methods *, void *, ph7_value *);
|
||||
PH7_PRIVATE int ph7_text_writer_emit(ph7_context *, int (*)(void *, const void *, unsigned int),
|
||||
void *, int nArg, ph7_value **, int bLine);
|
||||
/* Native callbacks backing the core TextWriter class (registered in classes.c). */
|
||||
PH7_PRIVATE int TextWriterConstruct(ph7_context *, int, ph7_value **);
|
||||
PH7_PRIVATE int TextWriterDestruct(ph7_context *, int, ph7_value **);
|
||||
PH7_PRIVATE int TextWriterClone(ph7_context *, int, ph7_value **);
|
||||
PH7_PRIVATE int TextWriterPrint(ph7_context *, int, ph7_value **);
|
||||
PH7_PRIVATE int TextWriterPrintLine(ph7_context *, int, ph7_value **);
|
||||
PH7_PRIVATE int TextWriterFlush(ph7_context *, int, ph7_value **);
|
||||
/* oo.c function prototypes */
|
||||
PH7_PRIVATE ph7_class_info *PH7_NewClassInfo(ph7_vm *pVm, const SyString *pName);
|
||||
PH7_PRIVATE ph7_class *PH7_NewRawClass(ph7_vm *pVm, const SyString *pName);
|
||||
@@ -1918,6 +1948,11 @@ PH7_PRIVATE const char *PH7_ExtractDirName(const char *zPath, int nByte, int *pL
|
||||
PH7_PRIVATE sxi32 PH7_RegisterIORoutine(ph7_vm *pVm);
|
||||
PH7_PRIVATE const ph7_vfs *PH7_ExportBuiltinVfs(void);
|
||||
PH7_PRIVATE void *PH7_ExportStdin(ph7_vm *pVm);
|
||||
PH7_PRIVATE void PH7_StdinUnread(ph7_vm *, unsigned char);
|
||||
PH7_PRIVATE int PH7_StdinReadCodepoint(ph7_vm *);
|
||||
/* Read one line from the shared stdin handle, including its line ending.
|
||||
* Returns NULL at EOF without data; the caller owns the returned bytes. */
|
||||
PH7_PRIVATE char *PH7_StdinReadLine(ph7_vm *pVm, int *pLen);
|
||||
PH7_PRIVATE void *PH7_ExportStdout(ph7_vm *pVm);
|
||||
PH7_PRIVATE void *PH7_ExportStderr(ph7_vm *pVm);
|
||||
/* lib.c function prototypes */
|
||||
|
||||
@@ -0,0 +1,668 @@
|
||||
/**
|
||||
* @PROJECT AerScript Interpreter
|
||||
* @COPYRIGHT See COPYING in the top level directory
|
||||
* @FILE modules/console/console.c
|
||||
* @DESCRIPTION Console class module for AerScript Interpreter
|
||||
* @DEVELOPERS Rafal Kupiec <belliash@codingworkshop.eu.org>
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#ifdef __WINNT__
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#include <sys/ioctl.h>
|
||||
#endif
|
||||
#include "console.h"
|
||||
|
||||
#ifndef STDERR_FILENO
|
||||
#define STDERR_FILENO 2
|
||||
#endif
|
||||
|
||||
/* .NET ConsoleColor values; published as COLOR_* constants. */
|
||||
enum console_color {
|
||||
COLOR_BLACK = 0, COLOR_BLUE = 9, COLOR_GREEN = 10, COLOR_CYAN = 11,
|
||||
COLOR_RED = 12, COLOR_MAGENTA = 13, COLOR_YELLOW = 14, COLOR_WHITE = 15,
|
||||
/* .NET spelling: only the underscored DARK_* names are published (D2). */
|
||||
COLOR_DARK_BLUE = 1, COLOR_DARK_GREEN = 2, COLOR_DARK_CYAN = 3,
|
||||
COLOR_DARK_RED = 4, COLOR_DARK_MAGENTA = 5, COLOR_DARK_YELLOW = 6,
|
||||
COLOR_GRAY = 7, COLOR_DARK_GRAY = 8
|
||||
};
|
||||
|
||||
/* Per-VM console state (C13). Colors are remembered even when output is
|
||||
* redirected: the terminal escape is emitted only for a real console. State
|
||||
* lives in the module slot owned by the VM, never in a process-global, so two
|
||||
* VMs cannot observe each other's colors. */
|
||||
typedef struct console_state {
|
||||
int nFgColor;
|
||||
int nBgColor;
|
||||
} console_state;
|
||||
|
||||
static void ConsoleStateRelease(void *pData) {
|
||||
free(pData);
|
||||
}
|
||||
static console_state *ConsoleState(ph7_vm *pVm) {
|
||||
console_state *pState = (console_state *)PH7_VmModuleData(pVm, "console");
|
||||
if(pState == 0) {
|
||||
pState = (console_state *)malloc(sizeof(*pState));
|
||||
if(pState) {
|
||||
pState->nFgColor = -1;
|
||||
pState->nBgColor = -1;
|
||||
if(PH7_VmSetModuleData(pVm, "console", pState, ConsoleStateRelease) != SXRET_OK) {
|
||||
free(pState);
|
||||
pState = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return pState;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Terminal helpers */
|
||||
/* ------------------------------------------------------------------ */
|
||||
static int ConsoleIsRedirected(int nFd) {
|
||||
#ifdef __WINNT__
|
||||
DWORD dwMode = 0;
|
||||
HANDLE h;
|
||||
switch(nFd) {
|
||||
case 0: h = GetStdHandle(STD_INPUT_HANDLE); break;
|
||||
case 2: h = GetStdHandle(STD_ERROR_HANDLE); break;
|
||||
default: h = GetStdHandle(STD_OUTPUT_HANDLE); break;
|
||||
}
|
||||
if(h == INVALID_HANDLE_VALUE || h == 0) {
|
||||
return 1;
|
||||
}
|
||||
if(!GetConsoleMode(h, &dwMode)) {
|
||||
return 1; /* A pipe or a redirected file. */
|
||||
}
|
||||
/* No side effects here: virtual terminal processing is enabled once at
|
||||
* module initialization (initializeModule), never from a query. */
|
||||
return 0;
|
||||
#else
|
||||
return isatty(nFd) ? 0 : 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* Positive decimal dimension from the environment, 0 when absent/invalid. */
|
||||
static int ConsoleEnvDim(const char *zName) {
|
||||
const char *z = getenv(zName);
|
||||
char *zEnd;
|
||||
long n;
|
||||
if(z == 0 || *z == 0) {
|
||||
return 0;
|
||||
}
|
||||
n = strtol(z, &zEnd, 10);
|
||||
if(zEnd == z || *zEnd != 0 || n < 1 || n > 0x7FFF) {
|
||||
return 0;
|
||||
}
|
||||
return (int)n;
|
||||
}
|
||||
static void ConsoleSize(int *pWidth, int *pHeight) {
|
||||
*pWidth = 0;
|
||||
*pHeight = 0;
|
||||
#ifdef __WINNT__
|
||||
{
|
||||
CONSOLE_SCREEN_BUFFER_INFO sInfo;
|
||||
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
if(h != INVALID_HANDLE_VALUE && GetConsoleScreenBufferInfo(h, &sInfo) &&
|
||||
sInfo.srWindow.Right >= sInfo.srWindow.Left && sInfo.srWindow.Bottom >= sInfo.srWindow.Top) {
|
||||
*pWidth = (int)(sInfo.srWindow.Right - sInfo.srWindow.Left + 1);
|
||||
*pHeight = (int)(sInfo.srWindow.Bottom - sInfo.srWindow.Top + 1);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
/* Under a harness stdout/stderr are pipes: try every standard descriptor
|
||||
* before falling back to the environment and finally the canonical 80x24.
|
||||
* Never report zero. */
|
||||
{
|
||||
int aFd[] = { 1, 2, 0 };
|
||||
unsigned int i;
|
||||
for(i = 0 ; i < SX_ARRAYSIZE(aFd) ; ++i) {
|
||||
#ifdef __UNIXES__
|
||||
struct winsize sWin;
|
||||
if(!ConsoleIsRedirected(aFd[i]) && ioctl(aFd[i], TIOCGWINSZ, &sWin) == 0 &&
|
||||
sWin.ws_col > 0 && sWin.ws_row > 0) {
|
||||
*pWidth = (int)sWin.ws_col;
|
||||
*pHeight = (int)sWin.ws_row;
|
||||
break;
|
||||
}
|
||||
#else
|
||||
(void)aFd[i];
|
||||
break;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
if(*pWidth < 1 || *pHeight < 1) {
|
||||
int nCols = ConsoleEnvDim("COLUMNS");
|
||||
int nRows = ConsoleEnvDim("LINES");
|
||||
*pWidth = nCols > 0 ? nCols : 80;
|
||||
*pHeight = nRows > 0 ? nRows : 24;
|
||||
}
|
||||
}
|
||||
|
||||
static void ConsoleEmit(ph7_context *pCtx, const char *zData) {
|
||||
if(!ConsoleIsRedirected(1)) {
|
||||
(void)ph7_context_output(pCtx, zData, -1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Writer backends */
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Standard output reuses the VM output consumer, so output buffers and
|
||||
* host consumers observe these bytes exactly as they observe print(). */
|
||||
static int ConsoleOutWrite(void *pUserData, const void *pData, unsigned int nByte) {
|
||||
ph7_vm *pVm = (ph7_vm *)pUserData;
|
||||
SyString sData;
|
||||
if(nByte == 0) {
|
||||
return SXRET_OK;
|
||||
}
|
||||
SyStringInitFromBuf(&sData, (const char *)pData, (int)nByte);
|
||||
return PH7_VmOutputConsume(pVm, &sData);
|
||||
}
|
||||
static int ConsoleOutFlush(void *pUserData) {
|
||||
SXUNUSED(pUserData);
|
||||
return SXRET_OK;
|
||||
}
|
||||
static void ConsoleOutRelease(void *pUserData) {
|
||||
SXUNUSED(pUserData);
|
||||
}
|
||||
/* Standard error bypasses ob_* and the VM consumer entirely. */
|
||||
static int ConsoleErrWrite(void *pUserData, const void *pData, unsigned int nByte) {
|
||||
const char *zData = (const char *)pData;
|
||||
unsigned int nDone = 0;
|
||||
SXUNUSED(pUserData);
|
||||
while(nDone < nByte) {
|
||||
#ifdef __WINNT__
|
||||
DWORD nWritten = 0;
|
||||
if(!WriteFile(GetStdHandle(STD_ERROR_HANDLE), zData + nDone, nByte - nDone, &nWritten, 0) || nWritten == 0) {
|
||||
return SXERR_ABORT;
|
||||
}
|
||||
nDone += (unsigned int)nWritten;
|
||||
#else
|
||||
ssize_t nWritten = write(STDERR_FILENO, zData + nDone, nByte - nDone);
|
||||
if(nWritten < 0) {
|
||||
return SXERR_ABORT;
|
||||
}
|
||||
nDone += (unsigned int)nWritten;
|
||||
#endif
|
||||
}
|
||||
return SXRET_OK;
|
||||
}
|
||||
static int ConsoleErrFlush(void *pUserData) {
|
||||
SXUNUSED(pUserData);
|
||||
return SXRET_OK;
|
||||
}
|
||||
static void ConsoleErrRelease(void *pUserData) {
|
||||
SXUNUSED(pUserData);
|
||||
}
|
||||
static const ph7_text_writer_methods sOutMethods = {
|
||||
ConsoleOutWrite, ConsoleOutFlush, ConsoleOutRelease
|
||||
};
|
||||
static const ph7_text_writer_methods sErrMethods = {
|
||||
ConsoleErrWrite, ConsoleErrFlush, ConsoleErrRelease
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Argument conversion helpers */
|
||||
/* ------------------------------------------------------------------ */
|
||||
static int ConsoleCtxWrite(void *pUserData, const void *pData, unsigned int nByte) {
|
||||
return ph7_context_output((ph7_context *)pUserData, (const char *)pData, (int)nByte);
|
||||
}
|
||||
|
||||
static int ConsolePrintImpl(ph7_context *pCtx, int nArg, ph7_value **apArg, int bLine) {
|
||||
/* One C implementation for every path: zero arguments emit only the EOL,
|
||||
* one argument is literal, several arguments use the first as the PH7
|
||||
* format. Validation lives in ph7_text_writer_emit() in the core. */
|
||||
return ph7_text_writer_emit(pCtx, ConsoleCtxWrite, pCtx, nArg, apArg, bLine);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Console method callbacks */
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Keep the legacy print() contract: the call is an expression whose value is
|
||||
* NULL, which matters for default-parameter sentinels. */
|
||||
static int ConsoleNullResult(ph7_context *pCtx, int rc) {
|
||||
return rc == SXRET_OK ? ph7_result_null(pCtx) : rc;
|
||||
}
|
||||
static int Console_Print(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
return ConsoleNullResult(pCtx, ConsolePrintImpl(pCtx, nArg, apArg, 0));
|
||||
}
|
||||
static int Console_PrintLine(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
return ConsoleNullResult(pCtx, ConsolePrintImpl(pCtx, nArg, apArg, 1));
|
||||
}
|
||||
static int Console_GetOut(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
ph7_value *pResult = ph7_context_new_scalar(pCtx);
|
||||
sxi32 rc;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
if(pResult == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
rc = ph7_text_writer_new(pCtx, &sOutMethods, pCtx->pVm, pResult);
|
||||
return rc == PH7_OK ? ph7_result_value(pCtx, pResult) : rc;
|
||||
}
|
||||
static int Console_GetError(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
ph7_value *pResult = ph7_context_new_scalar(pCtx);
|
||||
sxi32 rc;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
if(pResult == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
rc = ph7_text_writer_new(pCtx, &sErrMethods, 0, pResult);
|
||||
return rc == PH7_OK ? ph7_result_value(pCtx, pResult) : rc;
|
||||
}
|
||||
static int Console_Read(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
int cp;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
/* Read a whole UTF-8 sequence from the one stdin handle shared with
|
||||
* fgets()/fread(): a Unicode code point, 0xFFFD for invalid input, -1
|
||||
* at EOF. Unused look-ahead bytes are returned to the stream. */
|
||||
cp = PH7_StdinReadCodepoint(pCtx->pVm);
|
||||
return ph7_result_int(pCtx, cp);
|
||||
}
|
||||
static int Console_ReadLine(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
char *zLine;
|
||||
int nLen, rc;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
zLine = PH7_StdinReadLine(pCtx->pVm, &nLen);
|
||||
if(zLine == 0) {
|
||||
return ph7_result_null(pCtx);
|
||||
}
|
||||
/* Drop exactly one line feed and a carriage return only when it directly
|
||||
* precedes it: trailing bare CRs are data and must survive. */
|
||||
if(nLen > 0 && zLine[nLen - 1] == '\n') {
|
||||
--nLen;
|
||||
if(nLen > 0 && zLine[nLen - 1] == '\r') {
|
||||
--nLen;
|
||||
}
|
||||
}
|
||||
rc = ph7_result_string(pCtx, zLine, nLen);
|
||||
SyMemBackendFree(&pCtx->pVm->sAllocator, zLine);
|
||||
return rc;
|
||||
}
|
||||
static int Console_IsInputRedirected(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
return ph7_result_bool(pCtx, ConsoleIsRedirected(0));
|
||||
}
|
||||
static int Console_IsOutputRedirected(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
return ph7_result_bool(pCtx, ConsoleIsRedirected(1));
|
||||
}
|
||||
static int Console_IsErrorRedirected(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
return ph7_result_bool(pCtx, ConsoleIsRedirected(2));
|
||||
}
|
||||
static int Console_GetCommandLineArgs(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
ph7_value *pArray = ph7_context_new_array(pCtx);
|
||||
ph7_value *pEntry;
|
||||
SyBlob *pBlob;
|
||||
SyString *pFile;
|
||||
const char *zData, *zEntry;
|
||||
sxu32 nByte, nOfft = 0, nLen;
|
||||
sxi32 rc;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
if(pArray == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
/* Element 0 is the path of the MAIN script. pVm->aFiles[0] is installed by
|
||||
* PH7_VmPushFilePath() with bMain=TRUE and is already canonicalized with
|
||||
* SyRealPath(), so this is an ABSOLUTE path -- never the literal argv[0],
|
||||
* and never the path of an include file. For scripts compiled from memory
|
||||
* (stdin/eval) the placeholder is "[MEMORY]" and is published as "". */
|
||||
if(SySetUsed(&pCtx->pVm->aFiles) > 0) {
|
||||
pFile = *(SyString **)SySetAt(&pCtx->pVm->aFiles, 0);
|
||||
} else {
|
||||
pFile = 0;
|
||||
}
|
||||
pEntry = ph7_context_new_scalar(pCtx);
|
||||
if(pEntry == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
if(pFile && !(pFile->nByte == sizeof("[MEMORY]") - 1 &&
|
||||
SyMemcmp(pFile->zString, "[MEMORY]", sizeof("[MEMORY]") - 1) == 0)) {
|
||||
rc = ph7_value_string(pEntry, pFile->zString, (int)pFile->nByte);
|
||||
} else {
|
||||
rc = ph7_value_string(pEntry, "", 0);
|
||||
}
|
||||
if(rc != PH7_OK || ph7_array_add_elem(pArray, 0, pEntry) != PH7_OK) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
/* Remaining entries are the script arguments: pVm->sArgvEntries is the
|
||||
* very same list that backs $args, which is left untouched. */
|
||||
pBlob = &pCtx->pVm->sArgvEntries;
|
||||
nByte = SyBlobLength(pBlob);
|
||||
zData = (const char *)SyBlobData(pBlob);
|
||||
while(nOfft < nByte) {
|
||||
zEntry = zData + nOfft;
|
||||
nLen = SyStrlen(zEntry);
|
||||
pEntry = ph7_context_new_scalar(pCtx);
|
||||
if(pEntry == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
if(ph7_value_string(pEntry, zEntry, (int)nLen) != PH7_OK ||
|
||||
ph7_array_add_elem(pArray, 0, pEntry) != PH7_OK) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
nOfft += nLen + 1;
|
||||
}
|
||||
/* All entries are strings: stamp the primitive element type directly,
|
||||
* never PH7_VmInternType() (that makes a named class type). */
|
||||
pArray->nType = MEMOBJ_STRING | MEMOBJ_HASHMAP;
|
||||
return ph7_result_value(pCtx, pArray);
|
||||
}
|
||||
static int Console_Clear(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
#ifdef __WINNT__
|
||||
if(!ConsoleIsRedirected(1)) {
|
||||
CONSOLE_SCREEN_BUFFER_INFO sInfo;
|
||||
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
DWORD nWritten;
|
||||
COORD sOrigin = { 0, 0 };
|
||||
if(GetConsoleScreenBufferInfo(h, &sInfo)) {
|
||||
FillConsoleOutputCharacter(h, ' ', sInfo.dwSize.X * sInfo.dwSize.Y, sOrigin, &nWritten);
|
||||
FillConsoleOutputAttribute(h, sInfo.wAttributes, sInfo.dwSize.X * sInfo.dwSize.Y, sOrigin, &nWritten);
|
||||
SetConsoleCursorPosition(h, sOrigin);
|
||||
}
|
||||
}
|
||||
#else
|
||||
ConsoleEmit(pCtx, "\033[2J\033[H");
|
||||
#endif
|
||||
return PH7_OK;
|
||||
}
|
||||
static int Console_Beep(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
#ifdef __WINNT__
|
||||
MessageBeep(MB_OK);
|
||||
#else
|
||||
ConsoleEmit(pCtx, "\a");
|
||||
#endif
|
||||
return PH7_OK;
|
||||
}
|
||||
static int Console_SetTitle(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
const char *zTitle;
|
||||
int nLen;
|
||||
if(nArg < 1) {
|
||||
return PH7_OK;
|
||||
}
|
||||
zTitle = ph7_value_to_string(apArg[0], &nLen);
|
||||
if(pCtx->pVm->iPendingTransfer) {
|
||||
return pCtx->pVm->iPendingTransfer;
|
||||
}
|
||||
/* Reject control characters: an embedded BEL/OSC could forge terminal
|
||||
* escapes. No title or state is modified before this check. */
|
||||
{
|
||||
int i;
|
||||
for(i = 0 ; i < nLen ; ++i) {
|
||||
unsigned char c = (unsigned char)zTitle[i];
|
||||
if(c < 0x20 || c == 0x7F) {
|
||||
return PH7_VmThrowIoException(pCtx, 1, "Title contains a control character");
|
||||
}
|
||||
}
|
||||
}
|
||||
#ifdef __WINNT__
|
||||
if(!ConsoleIsRedirected(1)) {
|
||||
SetConsoleTitleA(zTitle);
|
||||
}
|
||||
#else
|
||||
if(!ConsoleIsRedirected(1)) {
|
||||
char *zBuf;
|
||||
zBuf = (char *)ph7_context_alloc_chunk(pCtx, (unsigned int)nLen + 6, FALSE, TRUE);
|
||||
if(zBuf) {
|
||||
memcpy(zBuf, "\033]0;", 4);
|
||||
memcpy(zBuf + 4, zTitle, (size_t)nLen);
|
||||
memcpy(zBuf + 4 + nLen, "\007", 1);
|
||||
(void)ph7_context_output(pCtx, zBuf, nLen + 5);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return PH7_OK;
|
||||
}
|
||||
static int Console_GetWidth(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
int nWidth, nHeight;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
ConsoleSize(&nWidth, &nHeight);
|
||||
return ph7_result_int(pCtx, nWidth);
|
||||
}
|
||||
static int Console_GetHeight(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
int nWidth, nHeight;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
ConsoleSize(&nWidth, &nHeight);
|
||||
return ph7_result_int(pCtx, nHeight);
|
||||
}
|
||||
static int Console_SetForegroundColor(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
int nColor;
|
||||
char zCode[16];
|
||||
console_state *pState;
|
||||
if(nArg < 1) {
|
||||
return PH7_OK;
|
||||
}
|
||||
nColor = ph7_value_to_int(apArg[0]);
|
||||
if(nColor < 0 || nColor > 15) {
|
||||
return PH7_VmThrowIoException(pCtx, 1, "Foreground color must be between 0 and 15");
|
||||
}
|
||||
pState = ConsoleState(pCtx->pVm);
|
||||
if(pState == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pState->nFgColor = nColor;
|
||||
#ifdef __WINNT__
|
||||
if(!ConsoleIsRedirected(1) && nColor >= 0 && nColor < 16) {
|
||||
static const WORD aColor[] = {
|
||||
0, FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_GREEN | FOREGROUND_BLUE,
|
||||
FOREGROUND_RED, FOREGROUND_RED | FOREGROUND_BLUE, FOREGROUND_RED | FOREGROUND_GREEN,
|
||||
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
|
||||
FOREGROUND_INTENSITY, FOREGROUND_INTENSITY | FOREGROUND_BLUE,
|
||||
FOREGROUND_INTENSITY | FOREGROUND_GREEN, FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE,
|
||||
FOREGROUND_INTENSITY | FOREGROUND_RED, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE,
|
||||
FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN,
|
||||
FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
|
||||
};
|
||||
CONSOLE_SCREEN_BUFFER_INFO sInfo;
|
||||
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
if(GetConsoleScreenBufferInfo(h, &sInfo)) {
|
||||
WORD wAttr = (sInfo.wAttributes & 0xF0) | aColor[nColor];
|
||||
SetConsoleTextAttribute(h, wAttr);
|
||||
}
|
||||
}
|
||||
#else
|
||||
if(!ConsoleIsRedirected(1) && nColor >= 0 && nColor < 16) {
|
||||
static const int aSgr[] = { 30, 34, 32, 36, 31, 35, 33, 37, 90, 94, 92, 96, 91, 95, 93, 97 };
|
||||
snprintf(zCode, sizeof(zCode), "\033[%dm", aSgr[nColor]);
|
||||
(void)ph7_context_output(pCtx, zCode, -1);
|
||||
}
|
||||
#endif
|
||||
return PH7_OK;
|
||||
}
|
||||
static int Console_SetBackgroundColor(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
int nColor;
|
||||
char zCode[16];
|
||||
console_state *pState;
|
||||
if(nArg < 1) {
|
||||
return PH7_OK;
|
||||
}
|
||||
nColor = ph7_value_to_int(apArg[0]);
|
||||
if(nColor < 0 || nColor > 15) {
|
||||
return PH7_VmThrowIoException(pCtx, 1, "Background color must be between 0 and 15");
|
||||
}
|
||||
pState = ConsoleState(pCtx->pVm);
|
||||
if(pState == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pState->nBgColor = nColor;
|
||||
#ifdef __WINNT__
|
||||
if(!ConsoleIsRedirected(1) && nColor >= 0 && nColor < 16) {
|
||||
static const WORD aColor[] = {
|
||||
0, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_GREEN | BACKGROUND_BLUE,
|
||||
BACKGROUND_RED, BACKGROUND_RED | BACKGROUND_BLUE, BACKGROUND_RED | BACKGROUND_GREEN,
|
||||
BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE,
|
||||
BACKGROUND_INTENSITY, BACKGROUND_INTENSITY | BACKGROUND_BLUE,
|
||||
BACKGROUND_INTENSITY | BACKGROUND_GREEN, BACKGROUND_INTENSITY | BACKGROUND_GREEN | BACKGROUND_BLUE,
|
||||
BACKGROUND_INTENSITY | BACKGROUND_RED, BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_BLUE,
|
||||
BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN,
|
||||
BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
|
||||
};
|
||||
CONSOLE_SCREEN_BUFFER_INFO sInfo;
|
||||
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
if(GetConsoleScreenBufferInfo(h, &sInfo)) {
|
||||
WORD wAttr = (sInfo.wAttributes & 0x0F) | aColor[nColor];
|
||||
SetConsoleTextAttribute(h, wAttr);
|
||||
}
|
||||
}
|
||||
#else
|
||||
if(!ConsoleIsRedirected(1) && nColor >= 0 && nColor < 16) {
|
||||
static const int aSgr[] = { 40, 44, 42, 46, 41, 45, 43, 47, 100, 104, 102, 106, 101, 105, 103, 107 };
|
||||
snprintf(zCode, sizeof(zCode), "\033[%dm", aSgr[nColor]);
|
||||
(void)ph7_context_output(pCtx, zCode, -1);
|
||||
}
|
||||
#endif
|
||||
return PH7_OK;
|
||||
}
|
||||
static int Console_GetForegroundColor(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
console_state *pState;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
pState = ConsoleState(pCtx->pVm);
|
||||
return ph7_result_int(pCtx, pState ? pState->nFgColor : -1);
|
||||
}
|
||||
static int Console_GetBackgroundColor(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
console_state *pState;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
pState = ConsoleState(pCtx->pVm);
|
||||
return ph7_result_int(pCtx, pState ? pState->nBgColor : -1);
|
||||
}
|
||||
static int Console_ResetColor(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
console_state *pState;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
pState = ConsoleState(pCtx->pVm);
|
||||
if(pState) {
|
||||
pState->nFgColor = -1;
|
||||
pState->nBgColor = -1;
|
||||
}
|
||||
#ifdef __WINNT__
|
||||
if(!ConsoleIsRedirected(1)) {
|
||||
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
|
||||
}
|
||||
#else
|
||||
ConsoleEmit(pCtx, "\033[0m");
|
||||
#endif
|
||||
return PH7_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Registration */
|
||||
/* ------------------------------------------------------------------ */
|
||||
static sxi32 ConsoleRegister(ph7_vm *pVm) {
|
||||
#define CTY(T) { PH7_TYPE_##T, 0, 0 }
|
||||
#define CONST_(N,V) { N, 0, PH7_MEMBER_PUBLIC, 0, 0 }
|
||||
static ph7_constant_def aConst[] = {
|
||||
CONST_("COLOR_BLACK", 0), CONST_("COLOR_DARK_BLUE", 1),
|
||||
CONST_("COLOR_DARK_GREEN", 2), CONST_("COLOR_DARK_CYAN", 3),
|
||||
CONST_("COLOR_DARK_RED", 4), CONST_("COLOR_DARK_MAGENTA", 5),
|
||||
CONST_("COLOR_DARK_YELLOW", 6), CONST_("COLOR_GRAY", 7),
|
||||
CONST_("COLOR_DARK_GRAY", 8), CONST_("COLOR_BLUE", 9),
|
||||
CONST_("COLOR_GREEN", 10), CONST_("COLOR_CYAN", 11),
|
||||
CONST_("COLOR_RED", 12), CONST_("COLOR_MAGENTA", 13),
|
||||
CONST_("COLOR_YELLOW", 14), CONST_("COLOR_WHITE", 15)
|
||||
};
|
||||
static const int aValue[] = {
|
||||
COLOR_BLACK, COLOR_DARK_BLUE, COLOR_DARK_GREEN, COLOR_DARK_CYAN,
|
||||
COLOR_DARK_RED, COLOR_DARK_MAGENTA, COLOR_DARK_YELLOW, COLOR_GRAY,
|
||||
COLOR_DARK_GRAY, COLOR_BLUE, COLOR_GREEN, COLOR_CYAN,
|
||||
COLOR_RED, COLOR_MAGENTA, COLOR_YELLOW, COLOR_WHITE
|
||||
};
|
||||
static const ph7_param_def aTitleParam[] = {
|
||||
{ "title", CTY(STRING), 0, 0, 0, 0 }
|
||||
};
|
||||
static const ph7_param_def aColorParam[] = {
|
||||
{ "color", CTY(INT), 0, 0, 0, 0 }
|
||||
};
|
||||
#define SM(NAME,RET,PARAMS,NPARAM,FUNC) \
|
||||
{ NAME, CTY(RET), PARAMS, NPARAM, FUNC, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC }
|
||||
#define SMV(NAME,RET,PARAMS,NPARAM,FUNC) \
|
||||
{ NAME, CTY(RET), PARAMS, NPARAM, FUNC, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC | PH7_MEMBER_VARIADIC }
|
||||
static const ph7_method_def aMethod[] = {
|
||||
SMV("Print", MIXED, 0, 0, Console_Print),
|
||||
SMV("PrintLine", MIXED, 0, 0, Console_PrintLine),
|
||||
SM("GetOut", OBJECT, 0, 0, Console_GetOut),
|
||||
SM("GetError", OBJECT, 0, 0, Console_GetError),
|
||||
SM("Read", INT, 0, 0, Console_Read),
|
||||
SM("ReadLine", MIXED, 0, 0, Console_ReadLine),
|
||||
SM("IsInputRedirected", BOOL, 0, 0, Console_IsInputRedirected),
|
||||
SM("IsOutputRedirected", BOOL, 0, 0, Console_IsOutputRedirected),
|
||||
SM("IsErrorRedirected", BOOL, 0, 0, Console_IsErrorRedirected),
|
||||
{ "GetCommandLineArgs", { PH7_TYPE_STRING, 0, 1 }, 0, 0,
|
||||
Console_GetCommandLineArgs, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
|
||||
SM("Clear", VOID, 0, 0, Console_Clear),
|
||||
SM("Beep", VOID, 0, 0, Console_Beep),
|
||||
SM("SetTitle", VOID, aTitleParam, 1, Console_SetTitle),
|
||||
SM("GetWidth", INT, 0, 0, Console_GetWidth),
|
||||
SM("GetHeight", INT, 0, 0, Console_GetHeight),
|
||||
SM("SetForegroundColor", VOID, aColorParam, 1, Console_SetForegroundColor),
|
||||
SM("SetBackgroundColor", VOID, aColorParam, 1, Console_SetBackgroundColor),
|
||||
SM("GetForegroundColor", INT, 0, 0, Console_GetForegroundColor),
|
||||
SM("GetBackgroundColor", INT, 0, 0, Console_GetBackgroundColor),
|
||||
SM("ResetColor", VOID, 0, 0, Console_ResetColor)
|
||||
};
|
||||
ph7_class_def sClass = {
|
||||
sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, "Console",
|
||||
0, 0, aConst, SX_ARRAYSIZE(aConst),
|
||||
aMethod, SX_ARRAYSIZE(aMethod), PH7_DECL_FINAL | PH7_DECL_VIRTUAL,
|
||||
0, 0, 0, 0, 0, 0
|
||||
};
|
||||
ph7_value *apValue[SX_ARRAYSIZE(aConst)];
|
||||
sxu32 n;
|
||||
sxi32 rc = PH7_OK;
|
||||
SyZero(apValue, sizeof(apValue));
|
||||
for(n = 0 ; n < SX_ARRAYSIZE(apValue) ; ++n) {
|
||||
apValue[n] = ph7_new_scalar(pVm);
|
||||
if(apValue[n] == 0) {
|
||||
rc = PH7_NOMEM;
|
||||
goto Cleanup;
|
||||
}
|
||||
ph7_value_int(apValue[n], aValue[n]);
|
||||
aConst[n].pValue = apValue[n];
|
||||
}
|
||||
rc = ph7_create_class(pVm, &sClass);
|
||||
Cleanup:
|
||||
for(n = 0 ; n < SX_ARRAYSIZE(apValue) ; ++n) {
|
||||
if(apValue[n]) {
|
||||
ph7_release_value(pVm, apValue[n]);
|
||||
aConst[n].pValue = 0;
|
||||
}
|
||||
}
|
||||
return rc;
|
||||
#undef SMV
|
||||
#undef SM
|
||||
#undef CONST_
|
||||
#undef CTY
|
||||
}
|
||||
|
||||
PH7_PRIVATE sxi32 initializeModule(ph7_vm *pVm, ph7_real *ver, SyString *desc) {
|
||||
#ifdef __WINNT__
|
||||
/* Enable virtual terminal processing once, at module initialization,
|
||||
* never from a redirected-state query. */
|
||||
DWORD dwMode = 0;
|
||||
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
if(h != INVALID_HANDLE_VALUE && GetConsoleMode(h, &dwMode) &&
|
||||
(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) == 0) {
|
||||
SetConsoleMode(h, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
|
||||
}
|
||||
#endif
|
||||
desc->zString = MODULE_DESC;
|
||||
*ver = MODULE_VER;
|
||||
return ConsoleRegister(pVm);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* @PROJECT AerScript Interpreter
|
||||
* @COPYRIGHT See COPYING in the top level directory
|
||||
* @FILE modules/console/console.h
|
||||
* @DESCRIPTION Console class module for AerScript Interpreter
|
||||
* @DEVELOPERS Rafal Kupiec <belliash@codingworkshop.eu.org>
|
||||
*/
|
||||
#ifndef __CONSOLE_H__
|
||||
#define __CONSOLE_H__
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "ph7.h"
|
||||
#include "ph7int.h"
|
||||
|
||||
#define MODULE_DESC "Console Module"
|
||||
#define MODULE_VER 1.0
|
||||
|
||||
PH7_PRIVATE sxi32 initializeModule(ph7_vm *pVm, ph7_real *ver, SyString *desc);
|
||||
|
||||
#endif
|
||||
+10
-9
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
private string num2Roman(int $num) {
|
||||
@@ -17,15 +18,15 @@ class Program {
|
||||
}
|
||||
|
||||
public void main() {
|
||||
print(' 7 => ' + $this->num2Roman(7) + "\n");
|
||||
print(' 9 => ' + $this->num2Roman(9) + "\n");
|
||||
print(' 11 => ' + $this->num2Roman(11) + "\n");
|
||||
print(' 42 => ' + $this->num2Roman(42) + "\n");
|
||||
print(' 105 => ' + $this->num2Roman(105) + "\n");
|
||||
print('1984 => ' + $this->num2Roman(1984) + "\n");
|
||||
print('1999 => ' + $this->num2Roman(1999) + "\n");
|
||||
print('2018 => ' + $this->num2Roman(2018) + "\n");
|
||||
print('2144 => ' + $this->num2Roman(2144) + "\n");
|
||||
Console::Print(' 7 => ' + $this->num2Roman(7) + "\n");
|
||||
Console::Print(' 9 => ' + $this->num2Roman(9) + "\n");
|
||||
Console::Print(' 11 => ' + $this->num2Roman(11) + "\n");
|
||||
Console::Print(' 42 => ' + $this->num2Roman(42) + "\n");
|
||||
Console::Print(' 105 => ' + $this->num2Roman(105) + "\n");
|
||||
Console::Print('1984 => ' + $this->num2Roman(1984) + "\n");
|
||||
Console::Print('1999 => ' + $this->num2Roman(1999) + "\n");
|
||||
Console::Print('2018 => ' + $this->num2Roman(2018) + "\n");
|
||||
Console::Print('2144 => ' + $this->num2Roman(2144) + "\n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
void test_assert(mixed $param) {
|
||||
@@ -6,7 +7,7 @@ class Program {
|
||||
|
||||
public void main() {
|
||||
callback $assert_fail = void(string $file, int $line, string $code) {
|
||||
print("Assertion failed ...\n");
|
||||
Console::Print("Assertion failed ...\n");
|
||||
};
|
||||
assert_options(ASSERT_ACTIVE, true);
|
||||
assert_options(ASSERT_BAIL, false);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Brainfuck {
|
||||
private string $code;
|
||||
private int $code_pointer;
|
||||
@@ -18,7 +19,7 @@ class Brainfuck {
|
||||
$this->interpret($this->code[$this->code_pointer]);
|
||||
$this->code_pointer++;
|
||||
}
|
||||
print($this->output);
|
||||
Console::Print($this->output);
|
||||
}
|
||||
|
||||
private void interpret(string $command) {
|
||||
@@ -95,11 +96,11 @@ class Program {
|
||||
sort($files);
|
||||
unset($file);
|
||||
for(int $n = 0; $n < sizeof($files); $n++) {
|
||||
print('Executing "' + $files[$n] + '"' + "\n");
|
||||
Console::Print('Executing "' + $files[$n] + '"' + "\n");
|
||||
$code = file_get_contents('tests/data/brainfuck/' + $files[$n]);
|
||||
$bf = new Brainfuck($code, $input);
|
||||
$bf->run();
|
||||
print("\n");
|
||||
Console::Print("\n");
|
||||
}
|
||||
closedir($dir);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
public void main(string[] $args) {
|
||||
callback $y = void() {
|
||||
callback $a = 'printf';
|
||||
callback $a = void(string $s) { Console::Print($s); };
|
||||
$a("I'm alive\n");
|
||||
var_dump($a);
|
||||
};
|
||||
@@ -10,6 +11,9 @@ class Program {
|
||||
var_dump($y);
|
||||
string $a = 'printf';
|
||||
var_dump($a);
|
||||
/* A string naming a builtin resolves as a callback value (C5). */
|
||||
callback $f = 'strtoupper';
|
||||
Console::PrintLine($f("builtin by name: " + "mixED"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
I'm alive
|
||||
callback(6 'printf')
|
||||
callback(11 '{closure_2}')
|
||||
callback(11 '{closure_1}')
|
||||
string(6 'printf')
|
||||
BUILTIN BY NAME: MIXED
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'math';
|
||||
import 'console';
|
||||
|
||||
class Program {
|
||||
|
||||
@@ -19,7 +20,7 @@ class Program {
|
||||
|
||||
public void main() {
|
||||
string $str = 'Example text';
|
||||
print($this->center_text($str));
|
||||
Console::Print($this->center_text($str));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Button {
|
||||
public callback $OnBeforeClick;
|
||||
public callback $OnAfterClick;
|
||||
@@ -9,7 +10,7 @@ class Button {
|
||||
|
||||
public void Click() {
|
||||
$this->DoBeforeClick();
|
||||
print('Click!');
|
||||
Console::Print('Click!');
|
||||
$this->DoAfterClick();
|
||||
}
|
||||
|
||||
@@ -33,8 +34,8 @@ class Program {
|
||||
|
||||
public void main() {
|
||||
object $MyWidget = new Button();
|
||||
$MyWidget->OnBeforeClick = void(object $Sender) { print($Sender->Name + ' (Before Click)'); };
|
||||
$MyWidget->OnAfterClick = void(object $Sender) { print($Sender->Name + ' (After Click)'); };
|
||||
$MyWidget->OnBeforeClick = void(object $Sender) { Console::Print($Sender->Name + ' (Before Click)'); };
|
||||
$MyWidget->OnAfterClick = void(object $Sender) { Console::Print($Sender->Name + ' (After Click)'); };
|
||||
$MyWidget->Click();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Operations {
|
||||
|
||||
public callback ops(int $x, int $y, string $op){
|
||||
@@ -26,11 +27,11 @@ class Program {
|
||||
callback $fn;
|
||||
object $op = new Operations();
|
||||
$fn = $op->ops(6, 7, 'ADD');
|
||||
print($fn() + "\n");
|
||||
Console::Print($fn() + "\n");
|
||||
$fn = $op->ops(6, 2, 'SUB');
|
||||
print($fn() + "\n");
|
||||
Console::Print($fn() + "\n");
|
||||
$fn = $op->ops(6, 7, 'MUL');
|
||||
print($fn() + "\n");
|
||||
Console::Print($fn() + "\n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
private const MY_CONST = 12 ^ 0x3FD;
|
||||
private callback $callback_test = void(){ print("Welcome everyone!\n");};
|
||||
private callback $callback_test = void(){ Console::Print("Welcome everyone!\n");};
|
||||
private static int $value = 4 + 4 * 4;
|
||||
|
||||
void callable(callback $callback = void(){ print("Hello world!\n");}) {
|
||||
void callable(callback $callback = void(){ Console::Print("Hello world!\n");}) {
|
||||
$callback();
|
||||
}
|
||||
|
||||
void complexArgs(string $name = 'AerScript' + $this->someStr(), int $age = 10*2+5) {
|
||||
print("Name = $name\n");
|
||||
print("Age = $age\n");
|
||||
Console::Print("Name = $name\n");
|
||||
Console::Print("Age = $age\n");
|
||||
}
|
||||
|
||||
string someStr() {
|
||||
@@ -33,10 +34,10 @@ class Program {
|
||||
$this->complexArgs();
|
||||
$this->complexArgs('Me');
|
||||
$this->callable();
|
||||
$this->callable(void(){ print("Welcome guest!\n");});
|
||||
$this->callable(void(){ Console::Print("Welcome guest!\n");});
|
||||
$this->callable($this->callback_test);
|
||||
$this->someTrue() || print("someTrue() failed\n");
|
||||
$this->someFalse() || print("someFalse() failed\n");
|
||||
$this->someTrue() || Console::Print("someTrue() failed\n");
|
||||
$this->someFalse() || Console::Print("someFalse() failed\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
private void test(int $a = (int(int $a, int $b, int $c){return $a+$b+$c;})(14, 10+2, 15), int $b = 0, int $c = 98) {
|
||||
print($a + PHP_EOL);
|
||||
print($b + PHP_EOL);
|
||||
print($c + PHP_EOL);
|
||||
Console::Print($a + PHP_EOL);
|
||||
Console::Print($b + PHP_EOL);
|
||||
Console::Print($c + PHP_EOL);
|
||||
}
|
||||
|
||||
public void main() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
class BaseClass {
|
||||
|
||||
protected void run() {
|
||||
printf('Test launched...');
|
||||
Console::Print('Test launched...');
|
||||
include 'data/includes/include_test.aer';
|
||||
}
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
printf("OK!\n");
|
||||
Console::Print("OK!\n");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
public void main() {
|
||||
@@ -9,13 +10,13 @@ class Program {
|
||||
if(array_key_exists('args', $backtrace[0])) {
|
||||
var_export($backtrace[0]['args']);
|
||||
} else {
|
||||
print("Cannot aquire arguments\n");
|
||||
Console::Print("Cannot aquire arguments\n");
|
||||
}
|
||||
return $p;
|
||||
}
|
||||
|
||||
void b(string $p1, string $p2, string $p3) {
|
||||
print("$p1, $p2, $p3");
|
||||
Console::Print("$p1, $p2, $p3");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import 'console';
|
||||
class Test1 {
|
||||
|
||||
public void __construct() {
|
||||
print("Test1::__construct() called.\n");
|
||||
Console::Print("Test1::__construct() called.\n");
|
||||
}
|
||||
|
||||
public void __destruct() {
|
||||
print("Test1::__destruct() called.\n");
|
||||
Console::Print("Test1::__destruct() called.\n");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,12 +14,12 @@ class Test1 {
|
||||
class Test2 extends Test1 {
|
||||
|
||||
public void __construct() {
|
||||
print("Test2::__construct() called.\n");
|
||||
Console::Print("Test2::__construct() called.\n");
|
||||
$parent->__construct();
|
||||
}
|
||||
|
||||
public void __destruct() {
|
||||
print("Test2::__destruct() called.\n");
|
||||
Console::Print("Test2::__destruct() called.\n");
|
||||
$parent->__destruct();
|
||||
}
|
||||
|
||||
@@ -28,16 +29,16 @@ class Program {
|
||||
object $test;
|
||||
|
||||
public void __construct() {
|
||||
print("Program::__construct() called.\n");
|
||||
Console::Print("Program::__construct() called.\n");
|
||||
$this->test = new Test1();
|
||||
}
|
||||
|
||||
public void __destruct() {
|
||||
print("Program::__destruct() called.\n");
|
||||
Console::Print("Program::__destruct() called.\n");
|
||||
}
|
||||
|
||||
public void main() {
|
||||
print("Program::main() called.\n");
|
||||
Console::Print("Program::main() called.\n");
|
||||
object $test = new Test2();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
// A simple C program to calculate Euler's Totient Function
|
||||
class Program {
|
||||
|
||||
@@ -22,7 +23,7 @@ class Program {
|
||||
public int main() {
|
||||
int $n;
|
||||
for($n = 1; $n <= 10; $n++)
|
||||
printf("phi(%d) = %d\n", $n, $this->phi($n));
|
||||
Console::Print("phi(%d) = %d\n", $n, $this->phi($n));
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import 'console';
|
||||
class ExceptionHandler {
|
||||
|
||||
public static void printException(Exception $e) {
|
||||
print('Uncaught ' + get_class($e) + ', code: ' + $e->getCode() + "\nMessage: " + htmlentities($e->getMessage()) + "\n");
|
||||
Console::Print('Uncaught ' + get_class($e) + ', code: ' + $e->getCode() + "\nMessage: " + htmlentities($e->getMessage()) + "\n");
|
||||
}
|
||||
|
||||
public static void handleException(Exception $e) {
|
||||
@@ -21,21 +22,21 @@ class Program {
|
||||
};
|
||||
set_exception_handler($handler);
|
||||
try {
|
||||
print("Called try block 0\n");
|
||||
Console::Print("Called try block 0\n");
|
||||
} finally {
|
||||
print("Called finally block 0\n");
|
||||
Console::Print("Called finally block 0\n");
|
||||
}
|
||||
try {
|
||||
throw new NewException("Catch me once", 1);
|
||||
} catch(Exception $e) {
|
||||
ExceptionHandler::handleException($e);
|
||||
} finally {
|
||||
print("Called finally block 1\n");
|
||||
Console::Print("Called finally block 1\n");
|
||||
}
|
||||
try {
|
||||
throw new NewException("Catch me twice", 2);
|
||||
} finally {
|
||||
print("Called finally block 2\n");
|
||||
Console::Print("Called finally block 2\n");
|
||||
}
|
||||
throw new Exception("Catch me thrice", 3);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
public void main() {
|
||||
bool $res = system("echo OK");
|
||||
print("Result: ", $res);
|
||||
Console::Print("Result: " + $res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Dog {
|
||||
public string $name;
|
||||
public string $color;
|
||||
@@ -9,7 +10,7 @@ class Dog {
|
||||
|
||||
public callback greet(string $greeting) {
|
||||
return void() using ($greeting) {
|
||||
print("$greeting, I am a {$this->color} dog named {$this->name}\n");
|
||||
Console::Print("$greeting, I am a {$this->color} dog named {$this->name}\n");
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
private int factorial(int $num) {
|
||||
@@ -9,7 +10,7 @@ class Program {
|
||||
|
||||
public void main() {
|
||||
int $num = 7;
|
||||
print('Factorial of ', $num, ' is ', $this->factorial($num), '.');
|
||||
Console::Print('Factorial of ' + $num + ' is ' + $this->factorial($num) + '.');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import 'console';
|
||||
class Circle {
|
||||
public void draw() {
|
||||
print("Circle\n");
|
||||
Console::Print("Circle\n");
|
||||
}
|
||||
}
|
||||
|
||||
class Square {
|
||||
public void draw() {
|
||||
print("Square\n");
|
||||
Console::Print("Square\n");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-10
@@ -1,30 +1,31 @@
|
||||
import 'console';
|
||||
class Test {
|
||||
|
||||
public void goto_test1() {
|
||||
int $i = 0;
|
||||
a:
|
||||
print("Foo $i\n");
|
||||
Console::Print("Foo $i\n");
|
||||
if($i > 5)
|
||||
goto b;
|
||||
$i++;
|
||||
goto a;
|
||||
b:
|
||||
print("Bar $i\n\n");
|
||||
Console::Print("Bar $i\n\n");
|
||||
}
|
||||
|
||||
public void goto_test2(int $a = 2) {
|
||||
switch($a) {
|
||||
case 1:
|
||||
print("\$a is 1\n\n");
|
||||
Console::Print("\$a is 1\n\n");
|
||||
goto out;
|
||||
case 2:
|
||||
print("\$a is 2\n\n");
|
||||
Console::Print("\$a is 2\n\n");
|
||||
goto out;
|
||||
case 3:
|
||||
print("\$a is 3\n\n");
|
||||
Console::Print("\$a is 3\n\n");
|
||||
goto out;
|
||||
case 4:
|
||||
print("\$a is 4\n\n");
|
||||
Console::Print("\$a is 4\n\n");
|
||||
goto out;
|
||||
}
|
||||
out:
|
||||
@@ -34,11 +35,11 @@ class Test {
|
||||
int $a = 10;
|
||||
a:
|
||||
$a--;
|
||||
print("$a\n");
|
||||
Console::Print("$a\n");
|
||||
if($a > 5) {
|
||||
goto a;
|
||||
}
|
||||
print("\n");
|
||||
Console::Print("\n");
|
||||
}
|
||||
|
||||
public void goto_test4() {
|
||||
@@ -47,9 +48,9 @@ class Test {
|
||||
int $c;
|
||||
hIterator: {
|
||||
$c = 0;
|
||||
print($headers[$pos], "\n");
|
||||
Console::Print($headers[$pos] + "\n");
|
||||
cIterator: {
|
||||
print(" ", $headers[$pos][$c], "\n");
|
||||
Console::Print(" " + $headers[$pos][$c] + "\n");
|
||||
if(strlen($headers[$pos]) <= ++$c) {
|
||||
goto cIteratorExit;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/local/bin/aer
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
/*
|
||||
@@ -6,7 +7,7 @@ class Program {
|
||||
* It does not take any arguments.
|
||||
*/
|
||||
public void main() {
|
||||
print('Hello world!'); // single line comment
|
||||
Console::Print('Hello world!'); // single line comment
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
require 'data/includes/base_class.aer';
|
||||
require 'data/includes/test_class.aer';
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
interface iVehicle {
|
||||
|
||||
public void drive();
|
||||
@@ -8,11 +9,11 @@ interface iVehicle {
|
||||
class Car implements iVehicle {
|
||||
|
||||
public void drive() {
|
||||
print("Driving...\n");
|
||||
Console::Print("Driving...\n");
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
print("Stopping...\n");
|
||||
Console::Print("Stopping...\n");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -20,7 +21,7 @@ class Car implements iVehicle {
|
||||
class MyCar extends Car {
|
||||
|
||||
public void drive() {
|
||||
print("Driving my car...\n");
|
||||
Console::Print("Driving my car...\n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
string encode_ip(string $dotquad_ip) {
|
||||
@@ -12,11 +13,11 @@ class Program {
|
||||
|
||||
public void main() {
|
||||
string $localhost = $this->encode_ip('127.0.0.1');
|
||||
print("127.0.0.1 ==> $localhost\n");
|
||||
Console::Print("127.0.0.1 ==> $localhost\n");
|
||||
string $router = $this->encode_ip('192.168.2.1');
|
||||
print("192.168.2.1 ==> $router\n");
|
||||
print("$localhost ==> ", $this->decode_ip($localhost) + PHP_EOL);
|
||||
print("$router ==> ", $this->decode_ip($router) + PHP_EOL);
|
||||
Console::Print("192.168.2.1 ==> $router\n");
|
||||
Console::Print("$localhost ==> " + ($this->decode_ip($localhost) + PHP_EOL));
|
||||
Console::Print("$router ==> " + ($this->decode_ip($router) + PHP_EOL));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
private int test() {
|
||||
@@ -15,9 +16,9 @@ class Program {
|
||||
} else if($z == 3) {
|
||||
break;
|
||||
}
|
||||
print("$z\n");
|
||||
Console::Print("$z\n");
|
||||
} while($a);
|
||||
print("$a\n");
|
||||
Console::Print("$a\n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
public void main() {
|
||||
@@ -11,10 +12,10 @@ class Program {
|
||||
if($b == 6) {
|
||||
break;
|
||||
}
|
||||
print("Hello variables: $a $b $c $d\n");
|
||||
Console::Print("Hello variables: $a $b $c $d\n");
|
||||
}
|
||||
}
|
||||
print("Variable \$c: $c\n");
|
||||
Console::Print("Variable \$c: $c\n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
public void main() {
|
||||
@@ -7,14 +8,14 @@ class Program {
|
||||
if($numeric == 6) {
|
||||
continue;
|
||||
}
|
||||
print("$key is $numeric\n");
|
||||
Console::Print("$key is $numeric\n");
|
||||
if($numeric == 8) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
print("\nA week has seven days:\n");
|
||||
Console::Print("\nA week has seven days:\n");
|
||||
foreach(string $day in $days) {
|
||||
print("$day\n");
|
||||
Console::Print("$day\n");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
private int test() {
|
||||
@@ -15,9 +16,9 @@ class Program {
|
||||
} else if($b == 3) {
|
||||
break;
|
||||
}
|
||||
print("$b\n");
|
||||
Console::Print("$b\n");
|
||||
}
|
||||
print("$c\n");
|
||||
Console::Print("$c\n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Luhn {
|
||||
private string $number;
|
||||
|
||||
@@ -33,9 +34,9 @@ class Program {
|
||||
while($i < $nums) {
|
||||
$luhn->setNumber($this->NUMBERS[$i]);
|
||||
if($luhn->validate()) {
|
||||
print('The number ' + $luhn->getNumber() + ' has passed the Luhn validation.' + "\n");
|
||||
Console::Print('The number ' + $luhn->getNumber() + ' has passed the Luhn validation.' + "\n");
|
||||
} else {
|
||||
print('The number ' + $luhn->getNumber() + ' has NOT passed the Luhn validation.' + "\n");
|
||||
Console::Print('The number ' + $luhn->getNumber() + ' has NOT passed the Luhn validation.' + "\n");
|
||||
}
|
||||
$i++;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import 'console';
|
||||
class Dog {
|
||||
|
||||
public void __invoke() {
|
||||
print("I am a dog!\n");
|
||||
Console::Print("I am a dog!\n");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
interface IntA {
|
||||
|
||||
public void test_a();
|
||||
@@ -13,7 +14,7 @@ interface IntB {
|
||||
class TestA {
|
||||
|
||||
public void test_a() {
|
||||
print("Hello world from TestA::test_a().\n");
|
||||
Console::Print("Hello world from TestA::test_a().\n");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,7 +22,7 @@ class TestA {
|
||||
class TestB {
|
||||
|
||||
public void test_b() {
|
||||
print("Hello world from TestB::test_b().\n");
|
||||
Console::Print("Hello world from TestB::test_b().\n");
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +31,7 @@ class TestB {
|
||||
class TestC {
|
||||
|
||||
public void test_c() {
|
||||
print("Hello world from TestC::test_c().\n");
|
||||
Console::Print("Hello world from TestC::test_c().\n");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -38,7 +39,7 @@ class TestC {
|
||||
class TestD {
|
||||
|
||||
public void test_a() {
|
||||
print("Hello world from TestD::test_a().\n");
|
||||
Console::Print("Hello world from TestD::test_a().\n");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -46,7 +47,7 @@ class TestD {
|
||||
class TestE {
|
||||
|
||||
public void test_b() {
|
||||
print("Hello world from TestE::test_b().\n");
|
||||
Console::Print("Hello world from TestE::test_b().\n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
string[] testArray() {
|
||||
@@ -5,16 +6,18 @@ class Program {
|
||||
}
|
||||
|
||||
callback[] testCallback() {
|
||||
return {'callme' => void() { print("Hello world\n"); }};
|
||||
return {'callme' => void() { Console::Print("Hello world\n"); }};
|
||||
}
|
||||
|
||||
public void main() {
|
||||
callback[] $constr = {'print'};
|
||||
print($this->testArray()['Machine'] + "\n");
|
||||
callback[] $constr = { void(string $s) { Console::Print($s); } };
|
||||
Console::Print($this->testArray()['Machine'] + "\n");
|
||||
$this->testCallback()['callme']();
|
||||
print(true ? "TRUE\n" : false ? "true\n" : "false\n");
|
||||
(void(string $name) { print("This should work too - $name.\n");})('AerScript');
|
||||
Console::Print(true ? "TRUE\n" : false ? "true\n" : "false\n");
|
||||
(void(string $name) { Console::Print("This should work too - $name.\n");})('AerScript');
|
||||
$constr[0]('Test finished.' + "\n");
|
||||
callback[] $map = {'up' => 'strtoupper', 'low' => 'strtolower'};
|
||||
Console::Print("%s|%s\n", $map['up']("UPPER/lower"), $map['low']("UPPER/lower"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -3,3 +3,4 @@ Hello world
|
||||
TRUE
|
||||
This should work too - AerScript.
|
||||
Test finished.
|
||||
UPPER/LOWER|upper/lower
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import 'console';
|
||||
class Test {
|
||||
public void __construct(string $a) {
|
||||
print("$a\n");
|
||||
Console::Print("$a\n");
|
||||
}
|
||||
|
||||
public void __construct(int $a, int $b) {
|
||||
print("$a + $b = ", $a + $b, "\n");
|
||||
Console::Print("$a + $b = " + ($a + $b) + "\n");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
public void count(int $a, int $b) {
|
||||
print("Counting 2 integers: $a + $b = ", $a + $b, "\n");
|
||||
Console::Print("Counting 2 integers: $a + $b = " + ($a + $b) + "\n");
|
||||
}
|
||||
|
||||
public void count(float $a, float $b) {
|
||||
print("Counting 2 floats: $a + $b = ", $a + $b, "\n");
|
||||
Console::Print("Counting 2 floats: $a + $b = " + ($a + $b) + "\n");
|
||||
}
|
||||
|
||||
public void main() {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
private int fun(int $y) {
|
||||
@@ -13,12 +14,12 @@ class Program {
|
||||
int $y = 5;
|
||||
for(int $x = 0; $x < $y; $x++) {
|
||||
for($z = 0; $z <= ($y - $x - 2); $z++) {
|
||||
print(' ');
|
||||
Console::Print(' ');
|
||||
}
|
||||
for($z = 0; $z <= $x; $z++) {
|
||||
print($this->fun($x) / ($this->fun($z) * $this->fun($x - $z)), ' ');
|
||||
Console::Print(($this->fun($x) / ($this->fun($z) * $this->fun($x - $z))) + ' ');
|
||||
}
|
||||
print("\n");
|
||||
Console::Print("\n");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
-20
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
private string $s = 'monkey';
|
||||
private string $t = 'many monkeys';
|
||||
@@ -11,29 +12,29 @@ class Program {
|
||||
}
|
||||
|
||||
private void testMonkey() {
|
||||
printf("[%s]\n", $this->s);
|
||||
printf("[%10s]\n", $this->s);
|
||||
printf("[%-10s]\n", $this->s);
|
||||
printf("[%010s]\n", $this->s);
|
||||
printf("[%'#10s]\n", $this->s);
|
||||
printf("[%10.10s]\n", $this->t);
|
||||
Console::Print("[%s]\n", $this->s);
|
||||
Console::Print("[%10s]\n", $this->s);
|
||||
Console::Print("[%-10s]\n", $this->s);
|
||||
Console::Print("[%010s]\n", $this->s);
|
||||
Console::Print("[%'#10s]\n", $this->s);
|
||||
Console::Print("[%10.10s]\n", $this->t);
|
||||
}
|
||||
|
||||
private void testNumbers() {
|
||||
printf("%%b = '%b'\n", $this->n);
|
||||
printf("%%c = '%c'\n", $this->c);
|
||||
printf("%%d = '%d'\n", $this->c);
|
||||
printf("%%d = '%d'\n", $this->n);
|
||||
printf("%%e = '%e'\n", $this->n);
|
||||
printf("%%u = '%u'\n", $this->n);
|
||||
printf("%%u = '%u'\n", $this->u);
|
||||
printf("%%f = '%f'\n", $this->n);
|
||||
printf("%%o = '%o'\n", $this->n);
|
||||
printf("%%s = '%s'\n", $this->n);
|
||||
printf("%%x = '%x'\n", $this->n);
|
||||
printf("%%X = '%X'\n", $this->n);
|
||||
printf("%%+d = '%+d'\n", $this->n);
|
||||
printf("%%+d = '%+d'\n", $this->u);
|
||||
Console::Print("%%b = '%b'\n", $this->n);
|
||||
Console::Print("%%c = '%c'\n", $this->c);
|
||||
Console::Print("%%d = '%d'\n", $this->c);
|
||||
Console::Print("%%d = '%d'\n", $this->n);
|
||||
Console::Print("%%e = '%e'\n", $this->n);
|
||||
Console::Print("%%u = '%u'\n", $this->n);
|
||||
Console::Print("%%u = '%u'\n", $this->u);
|
||||
Console::Print("%%f = '%f'\n", $this->n);
|
||||
Console::Print("%%o = '%o'\n", $this->n);
|
||||
Console::Print("%%s = '%s'\n", $this->n);
|
||||
Console::Print("%%x = '%x'\n", $this->n);
|
||||
Console::Print("%%X = '%X'\n", $this->n);
|
||||
Console::Print("%%+d = '%+d'\n", $this->n);
|
||||
Console::Print("%%+d = '%+d'\n", $this->u);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import 'console';
|
||||
final class Test {
|
||||
private int $value;
|
||||
|
||||
private void __construct() {
|
||||
print('Constructor called.' + "\n");
|
||||
Console::Print('Constructor called.' + "\n");
|
||||
}
|
||||
|
||||
private void __destruct() {
|
||||
print('Destructor called.' + "\n");
|
||||
Console::Print('Destructor called.' + "\n");
|
||||
}
|
||||
|
||||
/* This is singleton */
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'console';
|
||||
final virtual class Static {
|
||||
public static void test() {
|
||||
print('This method can be called statically...');
|
||||
Console::Print('This method can be called statically...');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
private string cycle(char $a, char $b, int $i = 0) {
|
||||
@@ -11,11 +12,11 @@ class Program {
|
||||
|
||||
public void main() {
|
||||
for(int $i = 1; $i < 3; $i++) {
|
||||
print($i + $this->cycle('a', 'b') + PHP_EOL);
|
||||
Console::Print($i + $this->cycle('a', 'b') + PHP_EOL);
|
||||
for(int $j = 1; $j < 5; $j++) {
|
||||
print(' ' + $j + $this->cycle('a', 'b', 1) + PHP_EOL);
|
||||
Console::Print(' ' + $j + $this->cycle('a', 'b', 1) + PHP_EOL);
|
||||
for(int $k = 1; $k < 3; $k++) {
|
||||
print(' ' + $k + $this->cycle('c', 'd', 2) + PHP_EOL);
|
||||
Console::Print(' ' + $k + $this->cycle('c', 'd', 2) + PHP_EOL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'math';
|
||||
import 'console';
|
||||
|
||||
class Sudoku {
|
||||
public int[] $board;
|
||||
@@ -36,9 +37,9 @@ class Sudoku {
|
||||
public void print() {
|
||||
for(int $r = 0; $r < $this->size; $r++) {
|
||||
for(int $d = 0; $d < $this->size; $d++) {
|
||||
print($this->board[$r][$d] + " ");
|
||||
Console::Print($this->board[$r][$d] + " ");
|
||||
}
|
||||
print("\n");
|
||||
Console::Print("\n");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,11 +94,11 @@ class Program {
|
||||
};
|
||||
object $sudoku = new Sudoku($board);
|
||||
$sudoku->print();
|
||||
print("=================\n");
|
||||
Console::Print("=================\n");
|
||||
if($sudoku->solve()) {
|
||||
$sudoku->print();
|
||||
} else {
|
||||
print("No solution found\n");
|
||||
Console::Print("No solution found\n");
|
||||
$sudoku->print();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
|
||||
public void main() {
|
||||
int $a = 1;
|
||||
switch($a) {
|
||||
case 0:
|
||||
print("very bad\n");
|
||||
Console::Print("very bad\n");
|
||||
break;
|
||||
case 1:
|
||||
print("very good\n");
|
||||
Console::Print("very good\n");
|
||||
case 2:
|
||||
print("good\n");
|
||||
Console::Print("good\n");
|
||||
break;
|
||||
default:
|
||||
print("bad");
|
||||
Console::Print("bad");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class StringTokenizer {
|
||||
private string $token;
|
||||
private string $delim;
|
||||
@@ -28,7 +29,7 @@ class Program {
|
||||
string $delim = " !@:\t\n";
|
||||
object $st = new StringTokenizer($str, $delim);
|
||||
while ($st->hasMoreTokens()) {
|
||||
print($st->nextToken(), "\n");
|
||||
Console::Print($st->nextToken() + "\n");
|
||||
}
|
||||
unset($st);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import 'console';
|
||||
class Hanoi {
|
||||
|
||||
public void towerOfHanoi(int $diskCount, int $fromPole, int $toPole, int $viaPole) {
|
||||
if($diskCount == 1) {
|
||||
printf('Move disk from pole ' + $fromPole + ' to pole ' + $toPole + "\n");
|
||||
Console::Print('Move disk from pole ' + $fromPole + ' to pole ' + $toPole + "\n");
|
||||
} else {
|
||||
$this->towerOfHanoi($diskCount - 1, $fromPole, $viaPole, $toPole);
|
||||
$this->towerOfHanoi(1, $fromPole, $toPole, $viaPole);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'console';
|
||||
class Program {
|
||||
private string $概要 = "AerScript Interpreter";
|
||||
|
||||
@@ -9,7 +10,7 @@ class Program {
|
||||
}
|
||||
|
||||
private void ダウンロード(){
|
||||
print($this->概要 + "\n");
|
||||
Console::Print($this->概要 + "\n");
|
||||
}
|
||||
|
||||
private bool isUTF8(string $str) {
|
||||
|
||||
Reference in New Issue
Block a user