wmi-1.3.16 from opsview.com

This commit is contained in:
Are Casilla
2019-02-16 00:16:52 +01:00
parent 163fdd3d1b
commit 17b3af2911
2146 changed files with 678824 additions and 0 deletions
@@ -0,0 +1,2 @@
ejs
future
@@ -0,0 +1,61 @@
#
# Makefile for Embedded Javascript (EJS)
#
# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
#
#
# Ejs may be linked into shared handlers so we must build the objects both
# shared and static if --shared was specified to configure.
#
COMPILE := *.c
EXPORT_OBJECTS := yes
PRE_DIRS := classes system db
MAKE_IFLAGS := -I../mpr -I../exml
include make.dep
ifeq ($(BLD_PRODUCT),ejs)
POST_DIRS := package
endif
ifeq ($(BLD_FEATURE_TEST),1)
POST_DIRS += test
endif
ifeq ($(BLD_FEATURE_EJS_DB),1)
LIBS += sqlite
endif
TARGETS += $(BLD_BIN_DIR)/libejs$(BLD_LIB)
TARGETS += $(BLD_BIN_DIR)/ejs$(BLD_EXE)
ifeq ($(BLD_FEATURE_EJS),1)
compileExtra: $(TARGETS)
endif
$(BLD_BIN_DIR)/libejs$(BLD_LIB): files \
$(shell BLD_OBJ=$(BLD_OBJ) \; BLD_OBJ_DIR=$(BLD_OBJ_DIR) \; \
eval echo `cat files`)
@bld --library $(BLD_BIN_DIR)/libejs \
--objectsDir $(BLD_OBJ_DIR) --objectList files \
--libs "exml mpr $(LIBS)"
$(BLD_BIN_DIR)/ejs$(BLD_EXE): $(BLD_BIN_DIR)/libejs$(BLD_LIB) \
$(BLD_BIN_DIR)/libmpr$(BLD_LIB) \
$(BLD_BIN_DIR)/libejs$(BLD_LIB) $(FILES)
@bld --executable $(BLD_BIN_DIR)/ejs$(BLD_EXE) \
--rpath "$(BLD_PREFIX)/bin" \
--preferStatic --smartLibs "ejs exml mpr $(LIBS)" \
--objectsDir $(BLD_OBJ_DIR) \
--objects "$(BLD_OBJ_DIR)/ejsCmd$(BLD_OBJ)"
cleanExtra:
@echo "rm -f $(TARGETS)" | $(BLDOUT)
@rm -f $(TARGETS)
@rm -f $(BLD_BIN_DIR)/libejs.*
## Local variables:
## tab-width: 4
## End:
## vim: tw=78 sw=4 ts=4
@@ -0,0 +1 @@
.updated
@@ -0,0 +1,21 @@
#
# Makefile to build the EJS Classes
#
# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
#
COMPILE := *.c
EXPORT_OBJECTS := yes
MAKE_IFLAGS := -I.. -I../../mpr -I../../exml
include make.dep
compileExtra: .updated
.updated: $(FILES)
@touch .updated
## Local variables:
## tab-width: 4
## End:
## vim: tw=78 sw=4 ts=4
@@ -0,0 +1,167 @@
/*
* @file ejsArray.c
* @brief Array class
*/
/********************************* Copyright **********************************/
/*
* @copy default
*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
* Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved.
*
* This software is distributed under commercial and open source licenses.
* You may use the GPL open source license described below or you may acquire
* a commercial license from Mbedthis Software. You agree to be fully bound
* by the terms of either license. Consult the LICENSE.TXT distributed with
* this software for full details.
*
* This software is open source; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See the GNU General Public License for more
* details at: http://www.mbedthis.com/downloads/gplLicense.html
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This GPL license does NOT permit incorporating this software into
* proprietary programs. If you are unable to comply with the GPL, you must
* acquire a commercial license to use this software. Commercial licenses
* for this software and support services are available from Mbedthis
* Software at http://www.mbedthis.com
*
* @end
*/
/********************************** Includes **********************************/
#include "ejs.h"
#if BLD_FEATURE_EJS
/************************************ Code ************************************/
int ejsDefineArrayClass(Ejs *ep)
{
if (ejsDefineClass(ep, "Array", "Object", ejsArrayConstructor) == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
return 0;
}
/******************************************************************************/
/*
* Routine to create the base array type
*/
EjsVar *ejsCreateArrayInternal(EJS_LOC_DEC(ep, loc), int size)
{
EjsProperty *pp;
EjsVar *obj, *vp;
/* MOB -- need to supply hash size -- max(size, 503)); */
obj = ejsCreateSimpleObjInternal(EJS_LOC_PASS(ep, loc), "Array");
if (obj == 0) {
mprAssert(0);
return obj;
}
obj->isArray = 1;
/* MOB -- call constructor here and replace this code */
pp = ejsSetPropertyToInteger(ep, obj, "length", size);
ejsMakePropertyEnumerable(pp, 0);
vp = ejsGetVarPtr(pp);
vp->isArrayLength = 1;
return obj;
}
/******************************************************************************/
EjsVar *ejsAddArrayElt(Ejs *ep, EjsVar *op, EjsVar *element,
EjsCopyDepth copyDepth)
{
EjsProperty *pp;
EjsVar *vp;
char idx[16];
int length;
mprAssert(op->isArray);
length = ejsGetPropertyAsInteger(ep, op, "length");
mprItoa(idx, sizeof(idx), length);
pp = ejsCreateProperty(ep, op, idx);
vp = ejsGetVarPtr(pp);
ejsWriteVar(ep, vp, element, copyDepth);
ejsSetPropertyToInteger(ep, op, "length", length + 1);
return vp;
}
/******************************************************************************/
/*
* Constructor
*/
int ejsArrayConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
EjsProperty *pp;
EjsVar *vp;
char idx[16];
int i, max;
thisObj->isArray = 1;
max = 0;
if (argc > 0) {
if (argc == 1 && ejsVarIsNumber(argv[0])) {
/*
* x = new Array(size);
*/
max = (int) ejsVarToInteger(argv[0]);
} else {
/*
* x = new Array(element0, element1, ..., elementN):
*/
max = argc;
for (i = 0; i < max; i++) {
mprItoa(idx, sizeof(idx), i);
pp = ejsCreateSimpleProperty(ep, thisObj, idx);
vp = ejsGetVarPtr(pp);
ejsWriteVar(ep, vp, argv[i], EJS_SHALLOW_COPY);
}
}
}
pp = ejsCreateSimpleProperty(ep, thisObj, "length");
ejsMakePropertyEnumerable(pp, 0);
vp = ejsGetVarPtr(pp);
ejsWriteVarAsInteger(ep, vp, max);
vp->isArrayLength = 1;
return 0;
}
/******************************************************************************/
#else
void ejsArrayDummy() {}
/******************************************************************************/
#endif /* BLD_FEATURE_EJS */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
+197
View File
@@ -0,0 +1,197 @@
/*
* @file ejsStndClasses.c
* @brief EJS support methods
*/
/********************************* Copyright **********************************/
/*
* @copy default
*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
* Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved.
*
* This software is distributed under commercial and open source licenses.
* You may use the GPL open source license described below or you may acquire
* a commercial license from Mbedthis Software. You agree to be fully bound
* by the terms of either license. Consult the LICENSE.TXT distributed with
* this software for full details.
*
* This software is open source; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See the GNU General Public License for more
* details at: http://www.mbedthis.com/downloads/gplLicense.html
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This GPL license does NOT permit incorporating this software into
* proprietary programs. If you are unable to comply with the GPL, you must
* acquire a commercial license to use this software. Commercial licenses
* for this software and support services are available from Mbedthis
* Software at http://www.mbedthis.com
*
* @end
*/
/********************************** Includes **********************************/
#include "ejs.h"
#if BLD_FEATURE_EJS && 0
/******************************************************************************/
/*
* Date constructor
*
* Date();
* Date(milliseconds);
* Date(dateString);
* Date(year, month, date);
* Date(year, month, date, hour, minute, second);
*/
int ejsDateConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
return 0;
}
/******************************************************************************/
static int load(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
const char *fileName;
XmlState *parser;
Exml *xp;
MprFile *file;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ep, EJS_ARG_ERROR, "Bad args. Usage: load(fileName);");
return -1;
}
fileName = argv[0]->string;
/* FUTURE -- not romable
Need rom code in MPR not MprServices
*/
file = mprOpen(ep, fileName, O_RDONLY, 0664);
if (file == 0) {
ejsError(ep, EJS_IO_ERROR, "Can't open: %s", fileName);
return -1;
}
xp = initParser(ep, thisObj, fileName);
parser = exmlGetParseArg(xp);
exmlSetInputStream(xp, readFileData, (void*) file);
if (exmlParse(xp) < 0) {
if (! ejsGotException(ep)) {
ejsError(ep, EJS_IO_ERROR, "Can't parse XML file: %s\nDetails %s",
fileName, exmlGetErrorMsg(xp));
}
termParser(xp);
mprClose(file);
return -1;
}
ejsSetReturnValue(ep, parser->nodeStack[0].obj);
termParser(xp);
mprClose(file);
return 0;
}
/******************************************************************************/
int ejsDefineDateClass(Ejs *ep)
{
EjsVar *dateClass;
dateClass = ejsDefineClass(ep, "Date", "Object", ejsDateConstructor);
if (dateClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
ejsDefineCMethod(ep, dateClass, "getDate", xxxProc, EJS_NO_LOCAL);
/* Returns "Friday" or 4 ? */
ejsDefineCMethod(ep, dateClass, "getDay", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "getMonth", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "getFullYear", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "getYear", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "getHours", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "getMinutes", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "getSeconds", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "getMilliseconds", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "getTime", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "getTimeZoneOffset", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "parse", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "setDate", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "setMonth", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "setFullYear", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "setYear", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "setMinutes", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "setSeconds", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "setMilliseconds", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "setTime", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "toString", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "toGMTString", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "toUTCString", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "toLocaleString", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "UTC", xxxProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, dateClass, "valueOf", xxxProc, EJS_NO_LOCAL);
/*
UTC: getUTCDate, getUTCDay, getUTCMonth, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCSeconds, getUTCMilliseconds
setUTCDate, setUTCDay, setUTCMonth, setUTCFullYear, setUTCHours,
setUTCMinutes, setUTCSeconds, setUTCMilliseconds
*/
return ejsObjHasErrors(dateClass) ? MPR_ERR_CANT_INITIALIZE : 0;
}
/******************************************************************************/
/*
Time is since 1970/01/01 GMT
Normal: Fri Feb 10 2006 05:06:44 GMT-0800 (Pacific Standard Time)
UTC: Sat, 11 Feb 2006 05:06:44 GMT
// Using without New
println(Date());
var myDate = new Date();
myDate.setFullYear(2010, 0, 14);
var today = new Date();
if (myDate > today) {
} else {
}
X=Date() should be equivalent to X=(new Date()).toString()
*/
/******************************************************************************/
#else
void ejsStndClassesDummy() {}
/******************************************************************************/
#endif /* BLD_FEATURE_EJS */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
+140
View File
@@ -0,0 +1,140 @@
/*
* @file ejsError.c
* @brief Error class
*/
/********************************* Copyright **********************************/
/*
* @copy default
*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
* Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved.
*
* This software is distributed under commercial and open source licenses.
* You may use the GPL open source license described below or you may acquire
* a commercial license from Mbedthis Software. You agree to be fully bound
* by the terms of either license. Consult the LICENSE.TXT distributed with
* this software for full details.
*
* This software is open source; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See the GNU General Public License for more
* details at: http://www.mbedthis.com/downloads/gplLicense.html
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This GPL license does NOT permit incorporating this software into
* proprietary programs. If you are unable to comply with the GPL, you must
* acquire a commercial license to use this software. Commercial licenses
* for this software and support services are available from Mbedthis
* Software at http://www.mbedthis.com
*
* @end
*/
/********************************** Includes **********************************/
#include "ejs.h"
#if BLD_FEATURE_EJS
/************************************ Code ************************************/
/*
* Parse the args and return the message. Convert non-string args using
* .toString.
*/
static char *getMessage(Ejs *ep, int argc, EjsVar **argv)
{
if (argc == 0) {
return "";
} else if (argc == 1) {
if (! ejsVarIsString(argv[0])) {
if (ejsRunMethod(ep, argv[0], "toString", 0) < 0) {
return 0;
}
return ep->result->string;
} else {
return argv[0]->string;
}
} else {
/* Don't call ejsError here or it will go recursive. */
return 0;
}
}
/******************************************************************************/
/*
* Error Constructor and also used for constructor for sub classes.
*
* Usage: new Error([message])
*/
int ejsErrorCons(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *msg, *stack;
msg = getMessage(ep, argc, argv);
if (msg == 0) {
return -1;
}
ejsSetPropertyToString(ep, thisObj, "name", ejsGetBaseClassName(thisObj));
ejsSetPropertyToString(ep, thisObj, "message", msg);
ejsSetPropertyToUndefined(ep, thisObj, "stack");
stack = ejsFormatStack(ep);
if (stack) {
ejsSetPropertyToString(ep, thisObj, "stack", stack);
mprFree(stack);
}
if (ejsObjHasErrors(thisObj)) {
return -1;
}
return 0;
}
/******************************************************************************/
int ejsDefineErrorClasses(Ejs *ep)
{
if (ejsDefineClass(ep, "Error", "Object", ejsErrorCons) == 0 ||
ejsDefineClass(ep, "AssertError", "Error", ejsErrorCons) == 0 ||
ejsDefineClass(ep, "EvalError", "Error", ejsErrorCons) == 0 ||
ejsDefineClass(ep, "InternalError", "Error", ejsErrorCons) == 0 ||
ejsDefineClass(ep, "IOError", "Error", ejsErrorCons) == 0 ||
ejsDefineClass(ep, "MemoryError", "Error", ejsErrorCons) == 0 ||
ejsDefineClass(ep, "RangeError", "Error", ejsErrorCons) == 0 ||
ejsDefineClass(ep, "ReferenceError", "Error", ejsErrorCons) == 0 ||
ejsDefineClass(ep, "SyntaxError", "Error", ejsErrorCons) == 0 ||
ejsDefineClass(ep, "TypeError", "Error", ejsErrorCons) == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
return 0;
}
/******************************************************************************/
#else
void ejsErrorDummy() {}
/******************************************************************************/
#endif /* BLD_FEATURE_EJS */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,588 @@
/*
* @file ejsObject.c
* @brief Object class
*/
/********************************* Copyright **********************************/
/*
* @copy default
*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
* Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved.
*
* This software is distributed under commercial and open source licenses.
* You may use the GPL open source license described below or you may acquire
* a commercial license from Mbedthis Software. You agree to be fully bound
* by the terms of either license. Consult the LICENSE.TXT distributed with
* this software for full details.
*
* This software is open source; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See the GNU General Public License for more
* details at: http://www.mbedthis.com/downloads/gplLicense.html
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This GPL license does NOT permit incorporating this software into
* proprietary programs. If you are unable to comply with the GPL, you must
* acquire a commercial license to use this software. Commercial licenses
* for this software and support services are available from Mbedthis
* Software at http://www.mbedthis.com
*
* @end
*/
/********************************** Includes **********************************/
#include "ejs.h"
#if BLD_FEATURE_EJS
/****************************** Forward Declarations **************************/
/*
* Support routines
*/
static void formatVar(Ejs *ep, MprBuf *bp, EjsVar *vp);
/******************************************************************************/
/*
* Routine to create an object of the desired class. Class name may
* contain "."
*
* The created object will be a stand-alone class NOT entered into the
* properties of any other object. Callers must do this if required. ClassName
* may contain "." and is interpreted relative to "obj" if supplied.
*
* Note: this does not call the constructors for the various objects and base
* classes.
*/
EjsVar *ejsCreateSimpleObjInternal(EJS_LOC_DEC(ep, loc), const char *className)
{
EjsVar *baseClass;
if (className && *className) {
baseClass = ejsGetClass(ep, 0, className);
if (baseClass == 0) {
mprError(ep, MPR_LOC, "Can't find base class %s", className);
return 0;
}
} else {
baseClass = 0;
}
return ejsCreateSimpleObjUsingClassInt(EJS_LOC_PASS(ep, loc),
baseClass);
}
/******************************************************************************/
/*
* Create an object based upon the specified base class object. It will be a
* stand-alone class not entered into the properties of any other object.
* Callers must do this if required.
*
* Note: this does not call the constructors for the various objects and base
* classes.
*/
EjsVar *ejsCreateSimpleObjUsingClassInt(EJS_LOC_DEC(ep, loc),
EjsVar *baseClass)
{
EjsVar *vp;
mprAssert(baseClass);
if (baseClass == 0) {
mprError(ep, MPR_LOC, "Missing base class\n");
return 0;
}
vp = ejsCreateObjVarInternal(EJS_LOC_PASS(ep, loc));
if (vp == 0) {
return vp;
}
ejsSetBaseClass(vp, baseClass);
/*
* This makes all internal method accesses faster
* NOTE: this code is duplicated in ejsCreateSimpleClass
*/
mprAssert(vp->objectState);
vp->objectState->methods = baseClass->objectState->methods;
return vp;
}
/******************************************************************************/
void ejsSetMethods(Ejs *ep, EjsVar *op)
{
op->objectState->methods = ep->global->objectState->methods;
}
/******************************************************************************/
/******************************** Internal Methods ****************************/
/******************************************************************************/
static EjsVar *createObjProperty(Ejs *ep, EjsVar *obj, const char *property)
{
return ejsGetVarPtr(ejsCreateSimpleProperty(ep, obj, property));
}
/******************************************************************************/
static int deleteObjProperty(Ejs *ep, EjsVar *obj, const char *property)
{
return ejsDeleteProperty(ep, obj, property);
}
/******************************************************************************/
static EjsVar *getObjProperty(Ejs *ep, EjsVar *obj, const char *property)
{
return ejsGetVarPtr(ejsGetSimpleProperty(ep, obj, property));
}
/******************************************************************************/
/*
* Set the value of a property. Create if it does not exist
*/
static EjsVar *setObjProperty(Ejs *ep, EjsVar *obj, const char *property,
const EjsVar *value)
{
EjsProperty *pp;
EjsVar *vp;
pp = ejsCreateSimpleProperty(ep, obj, property);
if (pp == 0) {
mprAssert(pp);
return 0;
}
vp = ejsGetVarPtr(pp);
if (ejsWriteVar(ep, vp, value, EJS_SHALLOW_COPY) < 0) {
mprAssert(0);
return 0;
}
return ejsGetVarPtr(pp);
}
/******************************************************************************/
/*********************************** Constructors *****************************/
/******************************************************************************/
#if UNUSED
/*
* Object constructor. We don't use this for speed. Think very carefully if
* you add an object constructor.
*/
int ejsObjectConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
return 0;
}
#endif
/******************************************************************************/
/******************************** Visible Methods *****************************/
/******************************************************************************/
static int cloneMethod(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
int copyDepth;
copyDepth = EJS_DEEP_COPY;
if (argc == 1 && ejsVarToBoolean(argv[0])) {
copyDepth = EJS_RECURSIVE_DEEP_COPY;
}
ejsWriteVar(ep, ep->result, thisObj, copyDepth);
return 0;
}
/******************************************************************************/
static int toStringMethod(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
MprBuf *bp;
int saveMaxDepth, saveDepth, saveFlags;
saveMaxDepth = ep->maxDepth;
if (argc >= 1) {
ep->maxDepth = ejsVarToInteger(argv[0]);
} else if (ep->maxDepth == 0) {
ep->maxDepth = MAXINT;
}
saveFlags = ep->flags;
if (argc >= 2) {
if (ejsVarToBoolean(argv[1])) {
ep->flags |= EJS_FLAGS_ENUM_HIDDEN;
}
}
if (argc == 3) {
if (ejsVarToBoolean(argv[2])) {
ep->flags |= EJS_FLAGS_ENUM_BASE;
}
}
bp = mprCreateBuf(ep, 0, 0);
saveDepth = ep->depth;
formatVar(ep, bp, thisObj);
ep->depth = saveDepth;
ep->maxDepth = saveMaxDepth;
mprAddNullToBuf(bp);
ejsWriteVarAsString(ep, ep->result, mprGetBufStart(bp));
mprFree(bp);
ep->flags = saveFlags;
return 0;
}
/******************************************************************************/
static int valueOfMethod(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 0) {
mprAssert(0);
return -1;
}
switch (thisObj->type) {
default:
case EJS_TYPE_UNDEFINED:
case EJS_TYPE_NULL:
case EJS_TYPE_CMETHOD:
case EJS_TYPE_OBJECT:
case EJS_TYPE_METHOD:
case EJS_TYPE_STRING_CMETHOD:
ejsWriteVar(ep, ep->result, thisObj, EJS_SHALLOW_COPY);
break;
case EJS_TYPE_STRING:
ejsWriteVarAsInteger(ep, ep->result, atoi(thisObj->string));
break;
case EJS_TYPE_BOOL:
case EJS_TYPE_INT:
#if BLD_FEATURE_INT64
case EJS_TYPE_INT64:
#endif
#if BLD_FEATURE_FLOATING_POINT
case EJS_TYPE_FLOAT:
#endif
ejsWriteVar(ep, ep->result, thisObj, EJS_SHALLOW_COPY);
break;
}
return 0;
}
/******************************************************************************/
static int hashGetAccessor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValueToInteger(ejs, (int) thisObj->objectState);
return 0;
}
/******************************************************************************/
static int classGetAccessor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (thisObj->objectState == 0 || thisObj->objectState->baseClass == 0) {
ejsSetReturnValueToString(ejs, "object");
} else {
ejsSetReturnValueToString(ejs,
thisObj->objectState->baseClass->objectState->className);
}
return 0;
}
/******************************************************************************/
/*
* Format an object. Called recursively to format properties and contained
* objects.
*/
static void formatVar(Ejs *ep, MprBuf *bp, EjsVar *vp)
{
EjsProperty *pp, *first;
EjsVar *propVar, *baseClass;
char *buf, *value;
int i;
if (vp->type == EJS_TYPE_OBJECT) {
if (!vp->objectState->visited) {
mprPutStringToBuf(bp, vp->isArray ? "[\n" : "{\n");
ep->depth++;
vp->objectState->visited = 1;
if (ep->depth <= ep->maxDepth) {
first = ejsGetFirstProperty(vp, EJS_ENUM_ALL);
if (ep->flags & EJS_FLAGS_ENUM_BASE) {
baseClass = vp->objectState->baseClass;
if (baseClass) {
for (i = 0; i < ep->depth; i++) {
mprPutStringToBuf(bp, " ");
}
mprPutStringToBuf(bp, baseClass->objectState->objName);
mprPutStringToBuf(bp, ": /* Base Class */ ");
if (baseClass->objectState == vp->objectState) {
value = "this";
} else if (ejsRunMethodCmd(ep, baseClass, "toString",
"%d", ep->maxDepth) < 0) {
value = "[object Object]";
} else {
mprAssert(ejsVarIsString(ep->result));
value = ep->result->string;
}
mprPutStringToBuf(bp, value);
if (first) {
mprPutStringToBuf(bp, ",\n");
}
}
}
pp = first;
while (pp) {
if (! pp->dontEnumerate ||
ep->flags & EJS_FLAGS_ENUM_HIDDEN) {
for (i = 0; i < ep->depth; i++) {
mprPutStringToBuf(bp, " ");
}
if (! vp->isArray) {
mprPutStringToBuf(bp, pp->name);
mprPutStringToBuf(bp, ": ");
}
propVar = ejsGetVarPtr(pp);
if (propVar->type == EJS_TYPE_OBJECT) {
if (pp->var.objectState == vp->objectState) {
value = "this";
} else if (ejsRunMethodCmd(ep, propVar,
"toString", "%d", ep->maxDepth) < 0) {
value = "[object Object]";
} else {
mprAssert(ejsVarIsString(ep->result));
value = ep->result->string;
}
mprPutStringToBuf(bp, value);
} else {
formatVar(ep, bp, &pp->var);
}
pp = ejsGetNextProperty(pp, EJS_ENUM_ALL);
if (pp) {
mprPutStringToBuf(bp, ",\n");
}
} else {
pp = ejsGetNextProperty(pp, EJS_ENUM_ALL);
}
}
}
vp->objectState->visited = 0;
mprPutCharToBuf(bp, '\n');
ep->depth--;
for (i = 0; i < ep->depth; i++) {
mprPutStringToBuf(bp, " ");
}
mprPutCharToBuf(bp, vp->isArray ? ']' : '}');
}
} else if (vp->type == EJS_TYPE_METHOD) {
mprPutStringToBuf(bp, "function (");
for (i = 0; i < vp->method.args->length; i++) {
mprPutStringToBuf(bp, vp->method.args->items[i]);
if ((i + 1) < vp->method.args->length) {
mprPutStringToBuf(bp, ", ");
}
}
mprPutStringToBuf(bp, ") {");
mprPutStringToBuf(bp, vp->method.body);
for (i = 0; i < ep->depth; i++) {
mprPutStringToBuf(bp, " ");
}
mprPutStringToBuf(bp, "}");
} else {
if (vp->type == EJS_TYPE_STRING) {
mprPutCharToBuf(bp, '\"');
}
/*
* We don't use ejsVarToString for arrays, objects and strings.
* This is because ejsVarToString does not call "obj.toString"
* and it is not required for strings.
* MOB - rc
*/
buf = ejsVarToString(ep, vp);
mprPutStringToBuf(bp, buf);
if (vp->type == EJS_TYPE_STRING) {
mprPutCharToBuf(bp, '\"');
}
}
}
/******************************************************************************/
/*
* mixin code. Blends code at the "thisObj" level.
*/
static int mixinMethod(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
EjsProperty *pp;
char *buf;
int fid, i, rc;
mprAssert(argv);
/*
* Create a variable scope block set to the current object
*/
rc = 0;
fid = ejsSetBlock(ep, thisObj);
for (i = 0; i < argc; i++) {
if (ejsVarIsString(argv[i])) {
rc = ejsEvalScript(ep, argv[i]->string, 0);
} else if (ejsVarIsObject(argv[i])) {
/* MOB -- OPT. When we have proper scope chains, we should just
refer to the module and not copy */
pp = ejsGetFirstProperty(argv[i], EJS_ENUM_ALL);
while (pp) {
ejsSetProperty(ep, thisObj, pp->name, ejsGetVarPtr(pp));
pp = ejsGetNextProperty(pp, EJS_ENUM_ALL);
}
} else {
/* MOB - rc */
buf = ejsVarToString(ep, argv[i]);
rc = ejsEvalScript(ep, buf, 0);
}
if (rc < 0) {
ejsCloseBlock(ep, fid);
return -1;
}
}
ejsCloseBlock(ep, fid);
return 0;
}
/******************************************************************************/
/*
* Create the object class
*/
int ejsDefineObjectClass(Ejs *ep)
{
EjsMethods *methods;
EjsProperty *objectProp, *protoProp;
EjsVar *op, *globalClass;
/*
* Must specially hand-craft the object class as it is the base class
* of all objects.
*/
op = ejsCreateObjVar(ep);
if (op == 0) {
return MPR_ERR_CANT_CREATE;
}
ejsSetClassName(ep, op, "Object");
/*
* Don't use a constructor for objects for speed
*/
ejsMakeClassNoConstructor(op);
/*
* MOB -- should mark properties as public / private and class or instance.
*/
ejsDefineCMethod(ep, op, "clone", cloneMethod, EJS_NO_LOCAL);
ejsDefineCMethod(ep, op, "toString", toStringMethod, EJS_NO_LOCAL);
ejsDefineCMethod(ep, op, "valueOf", valueOfMethod, EJS_NO_LOCAL);
ejsDefineCMethod(ep, op, "mixin", mixinMethod, EJS_NO_LOCAL);
ejsDefineCAccessors(ep, op, "hash", hashGetAccessor, 0, EJS_NO_LOCAL);
ejsDefineCAccessors(ep, op, "baseClass", classGetAccessor, 0, EJS_NO_LOCAL);
/*
* MOB -- make this an accessor
*/
protoProp = ejsSetProperty(ep, op, "prototype", op);
if (protoProp == 0) {
ejsFreeVar(ep, op);
return MPR_ERR_CANT_CREATE;
}
/*
* Setup the internal methods. Most classes will never override these.
* The XML class will. We rely on talloc to free internal. Use "ep" as
* the parent as we need "methods" to live while the interpreter lives.
*/
methods = mprAllocTypeZeroed(ep, EjsMethods);
op->objectState->methods = methods;
methods->createProperty = createObjProperty;
methods->deleteProperty = deleteObjProperty;
methods->getProperty = getObjProperty;
methods->setProperty = setObjProperty;
objectProp = ejsSetPropertyAndFree(ep, ep->global, "Object", op);
/*
* Change the global class to use Object's methods
*/
globalClass = ep->service->globalClass;
globalClass->objectState->methods = methods;
globalClass->objectState->baseClass = ejsGetVarPtr(protoProp);
ep->objectClass = ejsGetVarPtr(objectProp);
if (ejsObjHasErrors(ejsGetVarPtr(objectProp))) {
ejsFreeVar(ep, op);
return MPR_ERR_CANT_CREATE;
}
return 0;
}
/******************************************************************************/
#else
void ejsObjectDummy() {}
/******************************************************************************/
#endif /* BLD_FEATURE_EJS */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,144 @@
/*
* @file ejsStndClasses.c
* @brief EJS support methods
*/
/********************************* Copyright **********************************/
/*
* @copy default
*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
* Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved.
*
* This software is distributed under commercial and open source licenses.
* You may use the GPL open source license described below or you may acquire
* a commercial license from Mbedthis Software. You agree to be fully bound
* by the terms of either license. Consult the LICENSE.TXT distributed with
* this software for full details.
*
* This software is open source; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See the GNU General Public License for more
* details at: http://www.mbedthis.com/downloads/gplLicense.html
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This GPL license does NOT permit incorporating this software into
* proprietary programs. If you are unable to comply with the GPL, you must
* acquire a commercial license to use this software. Commercial licenses
* for this software and support services are available from Mbedthis
* Software at http://www.mbedthis.com
*
* @end
*/
/********************************** Includes **********************************/
#include "ejs.h"
#if BLD_FEATURE_EJS
/******************************************************************************/
/******************************* Function Class *******************************/
/******************************************************************************/
int ejsDefineFunctionClass(Ejs *ep)
{
if (ejsDefineClass(ep, "Function", "Object", ejsFunctionConstructor) == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
return 0;
}
/******************************************************************************/
/*
* Function constructor
*/
int ejsFunctionConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
int rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsArgError(ep, "Usage: Function(\"function (arg) { script };\");");
}
rc = ejsEvalScript(ep, argv[0]->string, 0);
/*
* Note: this will convert the object into a method. It will cease to be
* an object.
*/
if (rc == 0 && ejsVarIsMethod(ep->result)) {
/*
* Must make thisObj collectable.
*/
ejsMakeObjPermanent(thisObj, 0);
ejsMakeObjLive(thisObj, 1);
mprAssert(ejsObjIsCollectable(thisObj));
ejsWriteVar(ep, thisObj, ep->result, EJS_SHALLOW_COPY);
}
return rc;
}
/******************************************************************************/
/******************************* Boolean Class ********************************/
/******************************************************************************/
int ejsDefineBooleanClass(Ejs *ep)
{
if (ejsDefineClass(ep, "Boolean", "Object", ejsBooleanConstructor) == 0){
return MPR_ERR_CANT_INITIALIZE;
}
return 0;
}
/******************************************************************************/
/*
* Boolean constructor
*/
int ejsBooleanConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
return 0;
}
/******************************************************************************/
/******************************** Number Class ********************************/
/******************************************************************************/
int ejsDefineNumberClass(Ejs *ep)
{
if (ejsDefineClass(ep, "Number", "Object", ejsNumberConstructor) == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
return 0;
}
/******************************************************************************/
/*
* Number constructor
*/
int ejsNumberConstructor(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
return 0;
}
/******************************************************************************/
#else
void ejsStndClassesDummy() {}
/******************************************************************************/
#endif /* BLD_FEATURE_EJS */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,381 @@
/*
* @file ejsString.c
* @brief EJScript string class
*/
/********************************* Copyright **********************************/
/*
* @copy default
*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
* Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved.
*
* This software is distributed under commercial and open source licenses.
* You may use the GPL open source license described below or you may acquire
* a commercial license from Mbedthis Software. You agree to be fully bound
* by the terms of either license. Consult the LICENSE.TXT distributed with
* this software for full details.
*
* This software is open source; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See the GNU General Public License for more
* details at: http://www.mbedthis.com/downloads/gplLicense.html
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This GPL license does NOT permit incorporating this software into
* proprietary programs. If you are unable to comply with the GPL, you must
* acquire a commercial license to use this software. Commercial licenses
* for this software and support services are available from Mbedthis
* Software at http://www.mbedthis.com
*
* @end
*/
/********************************** Includes **********************************/
#include "ejs.h"
#if BLD_FEATURE_EJS
/******************************************************************************/
/*********************************** Constructors *****************************/
/******************************************************************************/
/*
* String constructor.
*/
int ejsStringConstructor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *str;
if (argc == 0) {
ejsSetReturnValueToString(ejs, "");
} else if (argc == 1) {
/* MOB -- rc */
str = ejsVarToString(ejs, argv[0]);
ejsSetReturnValueToString(ejs, str);
} else {
ejsArgError(ejs, "usage: String([var])");
return -1;
}
return 0;
}
/******************************************************************************/
/******************************** Visible Methods *****************************/
/******************************************************************************/
/*
* Return a string containing the character at a given index
*
* String string.charAt(Number)
*/
static int charAt(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
EjsNum num;
char buf[2];
if (argc != 1) {
ejsArgError(ejs, "usage: charAt(integer)");
return -1;
}
num = ejsVarToNumber(argv[0]);
if (num < 0 || num >= thisObj->length) {
ejsError(ejs, EJS_RANGE_ERROR, "Bad index");
return -1;
}
mprAssert(ejsVarIsString(thisObj));
buf[0] = argv[0]->string[num];
buf[1] = '\0';
ejsSetReturnValueToString(ejs, buf);
return 0;
}
/******************************************************************************/
/*
* Return an integer containing the character at a given index
*
* Number string.charCodeAt(Number)
*/
static EjsNum charCodeAt(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
EjsNum num;
if (argc != 1) {
ejsArgError(ejs, "usage: charCodeAt(integer)");
return -1;
}
num = ejsVarToNumber(argv[0]);
if (num < 0 || num >= thisObj->length) {
ejsError(ejs, EJS_RANGE_ERROR, "Bad index");
return -1;
}
ejsSetReturnValueToNumber(ejs, (EjsNum) argv[0]->string[num]);
return 0;
}
/******************************************************************************/
/*
* Catenate
*
* String string.catenate(var, ...)
*/
static int concat(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
int i;
if (argc == 0) {
ejsArgError(ejs, "usage: concat(String, ...)");
return -1;
}
mprAssert(ejsVarIsString(thisObj));
for (i = 0; i < argc; i++) {
if (ejsStrcat(ejs, thisObj, argv[i]) < 0) {
ejsMemoryError(ejs);
return -1;
}
}
ejsSetReturnValue(ejs, thisObj);
return 0;
}
/******************************************************************************/
/*
* Return the position of the first occurance of a substring
*
* Number string.indexOf(String subString [, Number start])
*/
static int indexOf(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *pat, *s1, *s2, *origin;
int start, i;
if (argc == 0 || argc > 2) {
ejsArgError(ejs, "usage: indexOf(String [, Number])");
return -1;
}
pat = ejsVarToString(ejs, argv[0]);
if (argc == 2) {
start = ejsVarToNumber(argv[1]);
if (start > thisObj->length) {
start = thisObj->length;
}
} else {
start = 0;
}
i = start;
for (origin = &thisObj->string[i]; i < thisObj->length; i++, origin++) {
s1 = origin;
for (s2 = pat; *s1 && *s2; s1++, s2++) {
if (*s1 != *s2) {
break;
}
}
if (*s2 == '\0') {
ejsSetReturnValueToNumber(ejs, (EjsNum) (origin - thisObj->string));
}
}
ejsSetReturnValueToNumber(ejs, (EjsNum) -1);
return 0;
}
/******************************************************************************/
/*
* Return the position of the last occurance of a substring
*
* Number string.lastIndexOf(String subString [, Number start])
*/
static int lastIndexOf(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *pat, *s1, *s2, *origin;
int start;
if (argc == 0 || argc > 2) {
ejsArgError(ejs, "usage: indexOf(String [, Number])");
return -1;
}
pat = ejsVarToString(ejs, argv[0]);
if (argc == 2) {
start = ejsVarToNumber(argv[1]);
if (start > thisObj->length) {
start = thisObj->length;
}
} else {
start = 0;
}
origin = &thisObj->string[thisObj->length - 1];
for (; origin >= &thisObj->string[start]; origin--) {
s1 = origin;
for (s2 = pat; *s1 && *s2; s1++, s2++) {
if (*s1 != *s2) {
break;
}
}
if (*s2 == '\0') {
ejsSetReturnValueToNumber(ejs, (EjsNum) (origin - thisObj->string));
}
}
ejsSetReturnValueToNumber(ejs, (EjsNum) -1);
return 0;
}
/******************************************************************************/
/*
* Return a substring
*
* Number string.slice(Number start, Number end)
*/
static int slice(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
EjsNum start, end;
if (argc != 2) {
ejsArgError(ejs, "usage: slice(Number, Number)");
return -1;
}
start = ejsVarToNumber(argv[0]);
end = ejsVarToNumber(argv[1]);
if (start < 0 || start >= thisObj->length) {
ejsError(ejs, EJS_RANGE_ERROR, "Bad start index");
return-1;
}
if (end < 0 || end >= thisObj->length) {
ejsError(ejs, EJS_RANGE_ERROR, "Bad end index");
return -1;
}
mprAssert(ejsVarIsString(thisObj));
ejsSetReturnValueToBinaryString(ejs, (uchar*) &thisObj->string[start],
end - start);
return 0;
}
/******************************************************************************/
/*
* Split a string
*
* Number string.split(String delimiter [, Number limit])
*/
static int split(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
EjsVar *array, *vp;
char *delim, *last, *cp;
int len, limit, alloc;
if (argc == 0 || argc > 2) {
ejsArgError(ejs, "usage: split(String [, Number])");
return -1;
}
delim = ejsVarToStringEx(ejs, argv[0], &alloc);
limit = ejsVarToNumber(argv[1]);
array = ejsCreateArray(ejs, 0);
len = strlen(delim);
last = thisObj->string;
for (cp = last; *cp; cp++) {
if (*cp == *delim && strncmp(cp, delim, len) == 0) {
if (cp > last) {
vp = ejsCreateBinaryStringVar(ejs, (uchar*) last, (cp - last));
ejsAddArrayElt(ejs, array, vp, EJS_SHALLOW_COPY);
ejsFreeVar(ejs, vp);
}
}
}
ejsSetReturnValue(ejs, array);
ejsFreeVar(ejs, array);
if (alloc) {
mprFree(delim);
}
return 0;
}
/******************************************************************************/
/*
* Create the object class
*/
int ejsDefineStringClass(Ejs *ejs)
{
EjsVar *sc;
sc = ejsDefineClass(ejs, "String", "Object", ejsStringConstructor);
if (sc == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
ejsDefineCMethod(ejs, sc, "charAt", charAt, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "charCodeAt", charCodeAt, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "concat", concat, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "indexOf", indexOf, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "lastIndexOf", lastIndexOf, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "slice", slice, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "split", split, EJS_NO_LOCAL);
#if UNUSED
ejsDefineCMethod(ejs, sc, "match", match, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "replace", replace, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "search", search, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "substring", substring, EJS_NO_LOCAL);
// MOB bad name
ejsDefineCMethod(ejs, sc, "substr", substr, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "toLowerCase", toLowerCase, EJS_NO_LOCAL);
ejsDefineCMethod(ejs, sc, "toUpperCase", toUpperCase, EJS_NO_LOCAL);
// Static method
ejsDefineCMethod(ejs, sc, "fromCharCode", fromCharCode, 0, EJS_NO_LOCAL);
#endif
if (ejsObjHasErrors(sc)) {
ejsFreeVar(ejs, sc);
return MPR_ERR_CANT_CREATE;
}
return 0;
}
/******************************************************************************/
#endif /* BLD_FEATURE_EJS */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+849
View File
@@ -0,0 +1,849 @@
/*
* ejs.h - EJScript Language (ECMAScript) header.
*/
/********************************* Copyright **********************************/
/*
* @copy default.g
*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
* Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved.
* Portions Copyright (c) GoAhead Software, 1995-2000. All Rights Reserved.
*
* This software is distributed under commercial and open source licenses.
* You may use the GPL open source license described below or you may acquire
* a commercial license from Mbedthis Software. You agree to be fully bound
* by the terms of either license. Consult the LICENSE.TXT distributed with
* this software for full details.
*
* This software is open source; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See the GNU General Public License for more
* details at: http://www.mbedthis.com/downloads/gplLicense.html
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This GPL license does NOT permit incorporating this software into
* proprietary programs. If you are unable to comply with the GPL, you must
* acquire a commercial license to use this software. Commercial licenses
* for this software and support services are available from Mbedthis
* Software at http://www.mbedthis.com
*
* @end
*/
/********************************** Includes **********************************/
#ifndef _h_EJS
#define _h_EJS 1
#include "mpr.h"
#include "ejsVar.h"
#ifdef __cplusplus
extern "C" {
#endif
/********************************* Prototypes *********************************/
/*
* Constants
*/
#if BLD_FEATURE_SQUEEZE
#define EJS_GC_WORK_QUOTA 160 /* Allocations required before
garbage colllection */
#define EJS_PARSE_INCR 256 /* Growth factor */
#define EJS_MAX_RECURSE 25 /* Sanity for maximum recursion */
#define EJS_SMALL_OBJ_HASH_SIZE 11 /* Small object hash size */
#define EJS_LIST_INCR 8 /* Growth increment for lists */
#define EJS_MAX_BACKTRACE 10 /* Recursion limit for assert */
#else
#define EJS_GC_WORK_QUOTA 500
#define EJS_PARSE_INCR 1024
#define EJS_MAX_RECURSE 100
#define EJS_SMALL_OBJ_HASH_SIZE 11
#define EJS_LIST_INCR 16
#define EJS_MAX_BACKTRACE 25
#endif
/*
* Allocation increments for the default interpreter
*/
#define EJS_DEFAULT_VAR_INC 8 /* Var allocation increment */
#define EJS_DEFAULT_PROP_INC 96 /* Property allocation increment */
#define EJS_DEFAULT_OBJ_INC 24 /* Object allocation increment */
#define EJS_DEFAULT_STR_INC 64 /* Object allocation increment */
#define EJS_MIN_TIME_FOR_GC 300 /**< Need 1/3 sec for GC */
#define EJS_GC_MIN_WORK_QUOTA 50 /**< Min to stop thrashing */
/*
* Allocation increments for all non-default interpreters
*/
#define EJS_VAR_INC 32
#define EJS_PROP_INC 64
#define EJS_OBJ_INC 64
#define EJS_STR_INC 64
#define EJS_INC_FRAMES 8 /* Frame stack increment */
#define EJS_MAX_FRAMES 64 /* Max frame stack */
/*
* Lexical analyser tokens
*/
#define EJS_TOK_ERR -1 /* Any error */
#define EJS_TOK_LPAREN 1 /* ( */
#define EJS_TOK_RPAREN 2 /* ) */
#define EJS_TOK_IF 3 /* if */
#define EJS_TOK_ELSE 4 /* else */
#define EJS_TOK_LBRACE 5 /* { */
#define EJS_TOK_RBRACE 6 /* } */
#define EJS_TOK_LOGICAL 7 /* ||, &&, ! */
#define EJS_TOK_EXPR 8 /* +, -, /, % */
#define EJS_TOK_SEMI 9 /* ; */
#define EJS_TOK_LITERAL 10 /* literal string */
#define EJS_TOK_METHOD_NAME 11 /* methodName( */
#define EJS_TOK_NEWLINE 12 /* newline white space */
#define EJS_TOK_ID 13 /* Identifier */
#define EJS_TOK_EOF 14 /* End of script */
#define EJS_TOK_COMMA 15 /* Comma */
#define EJS_TOK_VAR 16 /* var */
#define EJS_TOK_ASSIGNMENT 17 /* = */
#define EJS_TOK_FOR 18 /* for */
#define EJS_TOK_INC_DEC 19 /* ++, -- */
#define EJS_TOK_RETURN 20 /* return */
#define EJS_TOK_PERIOD 21 /* . */
#define EJS_TOK_LBRACKET 22 /* [ */
#define EJS_TOK_RBRACKET 23 /* ] */
#define EJS_TOK_NEW 24 /* new */
#define EJS_TOK_DELETE 25 /* delete */
#define EJS_TOK_IN 26 /* in */
#define EJS_TOK_FUNCTION 27 /* function */
#define EJS_TOK_NUMBER 28 /* Number */
#define EJS_TOK_CLASS 29 /* class */
#define EJS_TOK_EXTENDS 30 /* extends */
#define EJS_TOK_PUBLIC 31 /* public */
#define EJS_TOK_PRIVATE 32 /* private */
#define EJS_TOK_PROTECTED 33 /* private */
#define EJS_TOK_TRY 34 /* try */
#define EJS_TOK_CATCH 35 /* catch */
#define EJS_TOK_FINALLY 36 /* finally */
#define EJS_TOK_THROW 37 /* throw */
#define EJS_TOK_COLON 38 /* : */
#define EJS_TOK_GET 39 /* get */
#define EJS_TOK_SET 40 /* set */
#define EJS_TOK_MODULE 41 /* module */
#define EJS_TOK_EACH 42 /* each */
/*
* Expression operators
*/
#define EJS_EXPR_LESS 1 /* < */
#define EJS_EXPR_LESSEQ 2 /* <= */
#define EJS_EXPR_GREATER 3 /* > */
#define EJS_EXPR_GREATEREQ 4 /* >= */
#define EJS_EXPR_EQ 5 /* == */
#define EJS_EXPR_NOTEQ 6 /* != */
#define EJS_EXPR_PLUS 7 /* + */
#define EJS_EXPR_MINUS 8 /* - */
#define EJS_EXPR_DIV 9 /* / */
#define EJS_EXPR_MOD 10 /* % */
#define EJS_EXPR_LSHIFT 11 /* << */
#define EJS_EXPR_RSHIFT 12 /* >> */
#define EJS_EXPR_MUL 13 /* * */
#define EJS_EXPR_ASSIGNMENT 14 /* = */
#define EJS_EXPR_INC 15 /* ++ */
#define EJS_EXPR_DEC 16 /* -- */
#define EJS_EXPR_BOOL_COMP 17 /* ! */
/*
* Conditional operators
*/
#define EJS_COND_AND 1 /* && */
#define EJS_COND_OR 2 /* || */
#define EJS_COND_NOT 3 /* ! */
/**
* EJ Parsing States. Error and Return are be negative.
*/
#define EJS_STATE_ERR -1 /**< Error state */
#define EJS_STATE_RET -2 /**< Return statement */
#define EJS_STATE_EOF -3 /**< End of file */
#define EJS_STATE_COND 2 /* Parsing a conditional stmt */
#define EJS_STATE_COND_DONE 3
#define EJS_STATE_RELEXP 4 /* Parsing a relational expr */
#define EJS_STATE_RELEXP_DONE 5
#define EJS_STATE_EXPR 6 /* Parsing an expression */
#define EJS_STATE_EXPR_DONE 7
#define EJS_STATE_STMT 8 /* Parsing General statement */
#define EJS_STATE_STMT_DONE 9
#define EJS_STATE_STMT_BLOCK_DONE 10 /* End of block "}" */
#define EJS_STATE_ARG_LIST 11 /* Method arg list */
#define EJS_STATE_ARG_LIST_DONE 12
#define EJS_STATE_DEC_LIST 16 /* Declaration list */
#define EJS_STATE_DEC_LIST_DONE 17
#define EJS_STATE_DEC 18 /* Declaration statement */
#define EJS_STATE_DEC_DONE 19
#define EJS_STATE_BEGIN EJS_STATE_STMT
/*
* General parsing flags.
*/
#define EJS_FLAGS_EXE 0x1 /* Execute statements */
#define EJS_FLAGS_LOCAL 0x2 /* Get local vars only */
#define EJS_FLAGS_GLOBAL 0x4 /* Get global vars only */
#define EJS_FLAGS_CREATE 0x8 /* Create var */
#define EJS_FLAGS_ASSIGNMENT 0x10 /* In assignment stmt */
#define EJS_FLAGS_DELETE 0x20 /* Deleting a variable */
#define EJS_FLAGS_NEW 0x80 /* In a new stmt() */
#define EJS_FLAGS_EXIT 0x100 /* Must exit */
#define EJS_FLAGS_LHS 0x200 /* Left-hand-side of assignment */
#define EJS_FLAGS_FORIN 0x400 /* In "for (v in ..." */
#define EJS_FLAGS_CLASS_DEC 0x800 /* "class name [extends] name " */
#define EJS_FLAGS_TRY 0x2000 /* In a try {} block */
#define EJS_FLAGS_CATCH 0x4000 /* "catch (variable)" */
#define EJS_FLAGS_DONT_GC 0x8000 /* Don't garbage collect */
#define EJS_FLAGS_NO_ARGS 0x10000 /* Accessors don't use args */
#define EJS_FLAGS_ENUM_HIDDEN 0x20000 /* Enumerate hidden fields */
#define EJS_FLAGS_ENUM_BASE 0x40000 /* Enumerate base classes */
#define EJS_FLAGS_TRACE_ARGS 0x80000 /* Support for printv */
#define EJS_FLAGS_SHARED_SLAB 0x100000/* Using a shared slab */
/*
* Exceptions
*/
#define EJS_ARG_ERROR "ArgError" /**< Method argument error */
#define EJS_ASSERT_ERROR "AssertError" /**< Assertion error */
#define EJS_EVAL_ERROR "EvalError" /**< General evalation error */
#define EJS_INTERNAL_ERROR "InternalError" /**< Internal error */
#define EJS_IO_ERROR "IOError" /**< IO or data error */
#define EJS_MEMORY_ERROR "MemoryError" /**< Memory allocation error */
#define EJS_RANGE_ERROR "RangeError" /**< Data out of range (div by 0) */
#define EJS_REFERENCE_ERROR "ReferenceError"/**< Object or property reference */
#define EJS_SYNTAX_ERROR "SyntaxError" /**< Javascript syntax error */
#define EJS_TYPE_ERROR "TypeError" /**< Wrong type supplied */
/*
* E4X
*/
#if BLD_FEATURE_EJS_E4X
#if BLD_FEATURE_SQUEEZE
#define E4X_BUF_SIZE 512 /* Initial buffer size for tokens */
#define E4X_BUF_MAX (32 * 1024) /* Max size for tokens */
#define E4X_MAX_NODE_DEPTH 24 /* Max nesting of tags */
#else
#define E4X_BUF_SIZE 4096
#define E4X_BUF_MAX (128 * 1024)
#define E4X_MAX_NODE_DEPTH 128
#endif
#define E4X_MAX_ELT_SIZE (E4X_BUF_MAX-1)
#define E4X_TEXT_PROPERTY "-txt"
#define E4X_TAG_NAME_PROPERTY "-tag"
#define E4X_COMMENT_PROPERTY "-com"
#define E4X_ATTRIBUTES_PROPERTY "-att"
#define E4X_PI_PROPERTY "-pi"
#define E4X_PARENT_PROPERTY "-parent"
#endif
#if BLD_FEATURE_MULTITHREAD
/**
* Multithreaded lock function
*/
typedef void (*EjsLockFn)(void *lockData);
/**
* Multithreaded unlock function
*/
typedef void (*EjsUnlockFn)(void *lockData);
#endif
/*
* Token limits
*/
#define EJS_MAX_LINE 128 /* Maximum input line buffer */
#define EJS_MAX_TOKEN 640 /* Max input parse token */
#define EJS_TOKEN_STACK 3 /* Put back token stack */
/*
* Putback token
*/
typedef struct EjsToken {
char tokbuf[EJS_MAX_TOKEN];
int tid; /* Token ID */
} EjsToken;
/*
* EJ evaluation block structure
*/
typedef struct EjsInput {
EjsToken putBack[EJS_TOKEN_STACK]; /* Put back token stack */
int putBackIndex; /* Top of stack index */
char line[EJS_MAX_LINE]; /* Current line */
char *fileName; /* File or script name */
int lineLength; /* Current line length */
int lineNumber; /* Parse line number */
int lineColumn; /* Column in line */
struct EjsInput *next; /* Used for backtraces */
const char *procName; /* Gives name in backtrace */
const char *script; /* Input script for parsing */
char *scriptServp; /* Next token in the script */
int scriptSize; /* Length of script */
char tokbuf[EJS_MAX_TOKEN]; /* Current token */
int tid; /* Token ID */
char *tokEndp; /* Pointer past end of token */
char *tokServp; /* Pointer to next token char */
struct EjsInput *nextInput; /* Free list of input structs */
} EjsInput;
/*
* Method call structure
*/
typedef struct EjsProc {
MprArray *args; /* Args for method */
EjsVar *fn; /* Method definition */
char *procName; /* Method name */
} EjsProc;
/**
* @overview EJScript Service structure
* @description The EJScript service manages the overall language runtime. It
* is the factory that creates interpreter instances via ejsCreateInterp.
* The EJScript service creates a master interpreter that holds the
* standard language classes and properties. When user interpreters are
* created, they reference (without copying) the master interpreter to
* gain access to the standard classes and types.
* @stability Prototype.
* @library libejs.
* @see ejsOpenService, ejsCloseService, ejsCreateInterp, ejsDestoryInterp
*/
typedef struct EjsService {
EjsVar *globalClass; /* Global class */
struct Ejs *master; /* Master Interp inherited by all */
#if BLD_FEATURE_MULTITHREAD
EjsLockFn lock;
EjsUnlockFn unlock;
void *lockData;
#endif
} EjsService;
/*
* Memory statistics
*/
typedef struct EjsMemStats {
uint maxMem;
uint usedMem;
} EjsMemStats;
/*
* Garbage collection block alignment
*/
#define EJS_ALLOC_ALIGN(ptr) \
(((ptr) + sizeof(void*) - 1) & ~(sizeof(void*) - 1))
/*
* Default GC tune factors
*/
#define EJS_GC_START_THRESHOLD (32 * 1024)
/*
* The Garbage collector is a generational collector. It ages blocks and
* optimizes the mark / sweep algorithm to focus on new and recent blocks
*/
typedef enum EjsGeneration {
EJS_GEN_NEW = 0,
EJS_GEN_RECENT_1 = 1,
EJS_GEN_RECENT_2 = 2,
EJS_GEN_OLD = 3,
EJS_GEN_PERMANENT = 4,
EJS_GEN_MAX = 5,
} EjsGeneration;
/*
* Garbage collector control
*/
typedef struct EjsGC {
bool enable;
bool enableDemandCollect;
bool enableIdleCollect;
/*
* maxMemory should be set to be 95% of the real max memory limit
*/
uint maxMemory; /* Above this, Throw Memory exception. */
int workQuota; /* Quota of work before GC */
int workDone; /* Count of allocations */
int degraded; /* Have exceeded maxMemory */
/*
* Debug Levels 0-N (increases verbosity)
* 1 -- Sweep and collection count
* 2 -- Trace objects deleted
* 3 -- Trace objects marked
* 4 -- Print alloc report when needing a demand allocation
*
*/
int debugLevel; /* In debug mode */
int collecting; /* Running garbage collection */
uint collectionCount; /* Number of times GC ran */
#if BLD_DEBUG
int gcIndent; /* Indent formatting */
int objectsInUse; /* Objects currently reachable */
int propertiesInUse; /* Properties currently reachable */
#endif
} EjsGC;
/*
* Slab memory allocation
*/
typedef struct EjsSlab {
uint allocIncrement; /* Growth increment in slab */
uint size; /* Size of allocations */
EjsGCLink freeList; /* Free list (only next ptr is used) */
EjsObj *lastRecentBlock; /* Saved for GC age generations phase */
EjsGCLink allocList[EJS_GEN_MAX]; /* Allocated block list */
#if BLD_FEATURE_ALLOC_STATS
uint totalAlloc; /* Total count of allocation calls */
uint freeCount; /* Number of blocks on the slab freelist */
uint allocCount; /* Number of allocated blocks */
uint peakAllocated; /* Peak allocated */
uint peakFree; /* Peak on the free list */
uint totalReclaimed; /* Total blocks reclaimed on sweeps */
uint totalSweeps; /* Total sweeps */
#endif
} EjsSlab;
/**
* @overview EJ interpreter control structure.
* @description EJ allocates one control structure per active interpreter.
* The \ref ejsCreateInterp routine creates the Ejs structure and returns
* a reference to be used in subsequent EJ API calls.
* @stability Prototype.
* @library libejs.
* @see ejsCreateInterp, ejsDestroyInterp, ejsOpenService
*/
struct Ejs {
void *altHandle; /* Alternate callback handle */
bool castAlloc; /* True if castTemp is allocated */
char *castTemp; /* Temporary string for casting */
char *currentClass; /* Current class name */
EjsVar *currentObj; /* Ptr to current object */
EjsVar *thisObject; /* Ptr to current "this" */
EjsProperty *currentProperty; /* Ptr to current property */
EjsGC gc; /* Garbage collector control */
char *errorMsg; /* Error message */
char *fileName; /* File or script name */
int lineNumber; /* File line number */
int scriptStatus; /* Status to exit() */
int flags; /* Flags */
MprArray *frames; /* List of variable frames */
EjsVar *global; /* Global object */
EjsVar *objectClass; /* Object class */
int gotException; /* Exception thrown */
EjsInput *input; /* Input evaluation block */
int depth; /* Recursion depth */
EjsVar *local; /* Local object */
int maxDepth; /* Maximum depth for formatting */
void *primaryHandle; /* primary callback handle */
EjsProc *proc; /* Current method */
int recurseCount; /* Recursion counter */
EjsVar *result; /* Variable result */
int tid; /* Current token id */
char *token; /* Pointer to token string */
EjsVar tokenNumber; /* Parsed number */
EjsService *service; /* Service object */
void *userData; /* Method user data */
EjsSlab *slabs; /* Memory allocation slabs */
MprCtx slabAllocContext; /* Allocation context */
EjsInput *inputList; /* Free list of input structs */
#if BLD_FEATURE_MULTITHREAD
EjsLockFn lock; /* Lock method */
EjsUnlockFn unlock; /* Unlock method */
void *lockData; /* Lock data argument */
#endif
#define EJS_MAX_STACK (10 * 1024)
char stack[EJS_MAX_STACK]; /* Local variable stack */
char *stkPtr; /* Local variable stack ptr */
void *inputMarker; /* Recurse protection */
};
typedef struct EjsModule
{
int dummy;
} EjsModule;
/*
* Method callback when using Alternate handles. GaCompat uses these and
* passes the web server request structure via the altHandle.
*/
typedef void *EjsHandle;
typedef int (*EjsAltCMethod)(Ejs *ejs, EjsHandle altHandle,
EjsVar *thisObj, int argc, EjsVar **argv);
typedef int (*EjsAltStringCMethod)(Ejs *ejs, EjsHandle altHandle,
EjsVar *thisObj, int argc, char **argv);
/*
* API Constants
*/
#define EJS_USE_OWN_SLAB 1
/******************************** Internal API ********************************/
/*
* Ejs Lex
*/
extern int ejsLexOpenScript(Ejs *ejs, const char *script);
extern void ejsLexCloseScript(Ejs *ejs);
extern int ejsInitInputState(EjsInput *ip);
extern void ejsLexSaveInputState(Ejs *ejs, EjsInput* state);
extern void ejsLexFreeInputState(Ejs *ejs, EjsInput* state);
extern void ejsLexRestoreInputState(Ejs *ejs, EjsInput* state);
extern int ejsLexGetToken(Ejs *ejs, int state);
extern void ejsLexPutbackToken(Ejs *ejs, int tid, char *string);
/*
* Parsing
*/
extern int ejsParse(Ejs *ejs, int state, int flags);
extern int ejsGetFlags(Ejs *ejs);
/*
* Create variable scope blocks
*/
extern int ejsOpenBlock(Ejs *ejs);
extern int ejsSetBlock(Ejs *ejs, EjsVar *local);
extern int ejsCloseBlock(Ejs *ejs, int vid);
extern int ejsEvalBlock(Ejs *ejs, char *script, EjsVar *vp);
extern void ejsSetFileName(Ejs *ejs, const char *fileName);
/*
* Class definitions
*/
extern EjsVar *ejsCreateSimpleClass(Ejs *ejs, EjsVar *baseClass,
const char *className);
extern int ejsDefineObjectClass(Ejs *ejs);
extern int ejsDefineArrayClass(Ejs *ejs);
extern int ejsDefineBooleanClass(Ejs *ejs);
extern int ejsDefineErrorClasses(Ejs *ejs);
extern int ejsDefineFileClass(Ejs *ejs);
extern int ejsDefineFileSystemClass(Ejs *ejs);
extern int ejsDefineHTTPClass(Ejs *ejs);
extern int ejsDefineFunctionClass(Ejs *ejs);
extern int ejsDefineNumberClass(Ejs *ejs);
extern int ejsDefineStringClass(Ejs *ejs);
extern int ejsDefineDateClass(Ejs *ejs);
extern int ejsDefineStandardClasses(Ejs *ejs);
#if BLD_FEATURE_EJS_E4X
extern int ejsDefineXmlClasses(Ejs *ejs);
extern EjsVar *ejsCreateXml(Ejs *ejs);
#endif
#if BLD_FEATURE_EJS_DB
extern int ejsDefineDbClasses(Ejs *ejs);
#endif
/*
* System class definitions
*/
extern int ejsDefineSystemClasses(Ejs *ejs);
extern int ejsDefineSystemClass(Ejs *ejs);
extern int ejsDefineAppClass(Ejs *ejs);
extern int ejsDefineDebugClass(Ejs *ejs);
extern int ejsDefineLogClass(Ejs *ejs);
extern int ejsDefineMemoryClass(Ejs *ejs);
extern int ejsDefineGCClass(Ejs *ejs);
extern int ejsDefineGlobalProperties(Ejs *ejs);
extern int ejsTermSystemClasses(Ejs *ejs);
extern void ejsTermHTTPClass(Ejs *ejs);
extern int ejsCreateObjectModel(Ejs *ejs);
/*
* Class constructors
*/
extern int ejsArrayConstructor(Ejs *ejs, EjsVar *thisObj, int argc,
EjsVar **argv);
extern int ejsXmlConstructor(Ejs *ejs, EjsVar *thisObj, int argc,
EjsVar **argv);
extern int ejsXmlListConstructor(Ejs *ejs, EjsVar *thisObj, int argc,
EjsVar **argv);
extern int ejsBooleanConstructor(Ejs *ejs, EjsVar *thisObj, int argc,
EjsVar **agv);
extern int ejsFunctionConstructor(Ejs *ejs, EjsVar *thisObj, int argc,
EjsVar **agv);
extern int ejsNumberConstructor(Ejs *ejs, EjsVar *thisObj, int argc,
EjsVar **argv);
extern int ejsStringConstructor(Ejs *ejs, EjsVar *thisObj, int argc,
EjsVar **argv);
extern int ejsDateConstructor(Ejs *ejs, EjsVar *thisObj,
int argc, EjsVar **argv);
/*
* Garbage collection
*/
extern void ejsGCInit(Ejs *ejs, int objInc, int propInc, int varInc,
int strInc);
extern int ejsIsTimeForGC(Ejs *ep, int timeTillNextEvent);
extern bool ejsSetGCDebugLevel(Ejs *ep, int debugLevel);
extern void ejsSweepAll(Ejs *ep);
extern EjsObj *ejsAllocObj(EJS_LOC_DEC(ejs, loc));
extern EjsProperty *ejsAllocProperty(EJS_LOC_DEC(ejs, loc));
extern EjsVar *ejsAllocVar(EJS_LOC_DEC(ejs, loc));
extern void ejsFree(Ejs *ejs, void *ptr, int slabIndex);
extern int ejsCollectGarbage(Ejs *ejs, int slabIndex);
extern int ejsIncrementalCollectGarbage(Ejs *ejs);
#if BLD_DEBUG
extern void ejsDumpObjects(Ejs *ejs);
#endif
#if BLD_FEATURE_ALLOC_STATS
extern void ejsPrintAllocReport(Ejs *ejs, bool printLeakReport);
#endif
extern void ejsCleanInterp(Ejs *ejs, bool doStats);
extern void ejsSetInternalMethods(Ejs *ejs, EjsVar *op);
extern void ejsSetPrimaryHandle(Ejs *ep, void *primaryHandle);
extern void ejsSetAlternateHandle(Ejs *ep, void *alternateHandle);
extern void *ejsGetUserData(Ejs *ejs);
/*
* Could possibly make these routines public
*/
extern int ejsSetGCMaxMemory(Ejs *ep, uint maxMemory);
extern uint ejsGetUsedMemory(Ejs *ejs);
extern uint ejsGetAllocatedMemory(Ejs *ejs);
extern uint ejsGetAvailableMemory(Ejs *ejs);
extern char *ejsFormatStack(Ejs* ep);;
/********************************* Prototypes *********************************/
#if BLD_FEATURE_MULTITHREAD
extern int ejsSetServiceLocks(EjsService *sp, EjsLockFn lock,
EjsUnlockFn unlock, void *data);
#endif
/*
* Ejs service and interpreter management
*/
extern EjsService *ejsOpenService(MprCtx ctx);
extern void ejsCloseService(EjsService *sp, bool doStats);
extern Ejs *ejsCreateInterp(EjsService *sp, void *primaryHandle,
void *altHandle, EjsVar *global, bool useOwnSlab);
extern void ejsDestroyInterp(Ejs *ejs, bool doStats);
extern Ejs *ejsGetMasterInterp(EjsService *sp);
extern EjsVar *ejsGetGlobalClass(Ejs *ejs);
/*
* Module support
*/
extern EjsModule *ejsCreateModule(const char *name, const char *version,
int (*start)(EjsModule*), int (*stop)(EjsModule*));
/*
* Native Objects
*/
void ejsSetNativeData(EjsVar *obj, void *data);
void ejsSetNativeHelpers(Ejs *ejs, EjsVar *nativeClass,
int (*createInstance)(Ejs *ejs, EjsVar *thisObj, int argc,
EjsVar **argv),
void (*disposeInstance)(Ejs *ejs, EjsVar *thisObj),
bool (*hasProperty)(Ejs *ejs, EjsVar *thisObj, const char *prop),
int (*deleteProperty)(Ejs *ejs, EjsVar *thisObj, const char *prop),
int (*getProperty)(Ejs *ejs, EjsVar *thisObj, const char *prop,
EjsVar *dest),
int (*setProperty)(Ejs *ejs, EjsVar *thisObj, const char *prop,
EjsVar *value),
int (*doOperator)(Ejs *ejs, EjsVar *thisObj, EjsOp *op, EjsVar
*result, EjsVar *lhs, EjsVar *rhs, int *code)
);
/*
* Evaluation methods
*/
extern int ejsEvalFile(Ejs *ejs, const char *path, EjsVar *result);
extern int ejsEvalScript(Ejs *ejs, const char *script, EjsVar *result);
extern int ejsRunMethod(Ejs *ejs, EjsVar *obj,
const char *methodName, MprArray *args);
extern int ejsRunMethodCmd(Ejs *ejs, EjsVar *obj,
const char *methodName, const char *cmdFmt, ...);
extern EjsVar *ejsGetReturnValue(Ejs *ejs);
extern EjsVar *ejsGetLocalObj(Ejs *ejs);
extern EjsVar *ejsGetGlobalObj(Ejs *ejs);
/*
* Define a class in the specified interpreter. If used with the default
* interpeter, then the class is defined for all interpreters.
*/
extern EjsVar *ejsDefineClass(Ejs *ejs, const char *className,
const char *extends, EjsCMethod constructor);
extern EjsVar *ejsGetClass(Ejs *ejs, EjsVar *parentClass,
const char *className);
extern const char *ejsGetClassName(EjsVar *obj);
extern const char *ejsGetBaseClassName(EjsVar *obj);
extern bool ejsIsSubClass(EjsVar *target, EjsVar *baseClass);
extern EjsVar *ejsGetBaseClass(EjsVar *obj);
extern void ejsSetBaseClass(EjsVar *obj, EjsVar *baseClass);
#define ejsCreateSimpleObj(ejs, className) \
ejsCreateSimpleObjInternal(EJS_LOC_ARGS(ejs), className)
extern EjsVar *ejsCreateSimpleObjInternal(EJS_LOC_DEC(ejs, loc),
const char *className);
#define ejsCreateSimpleObjUsingClass(ejs, baseClass) \
ejsCreateSimpleObjUsingClassInt(EJS_LOC_ARGS(ejs), \
baseClass)
extern EjsVar *ejsCreateSimpleObjUsingClassInt(EJS_LOC_DEC(ejs, loc),
EjsVar *baseClass);
/*
* This will create an object and call all required constructors
*/
extern EjsVar *ejsCreateObj(Ejs *ejs, EjsVar *obj,
const char *className, const char *constructorArgs);
#define ejsCreateObjUsingArgv(ejs, obj, className, args) \
ejsCreateObjUsingArgvInternal(EJS_LOC_ARGS(ejs), obj, \
className, args)
extern EjsVar *ejsCreateObjUsingArgvInternal(EJS_LOC_DEC(ejs, loc),
EjsVar *obj, const char *className, MprArray *args);
#define ejsCreateArray(ejs, size) \
ejsCreateArrayInternal(EJS_LOC_ARGS(ejs), size)
extern EjsVar *ejsCreateArrayInternal(EJS_LOC_DEC(ejs, loc),
int size);
/*
* Array methods. MOB -- need other array methods
*/
/* MOB -- spell out element */
extern EjsVar *ejsAddArrayElt(Ejs *ejs, EjsVar *op, EjsVar *element,
EjsCopyDepth copyDepth);
/*
* Required: Array methods
*
array = obj.getMethods();
array = obj.getProperties();
array.property.isPublic();
array.property.isPrivate();
array.property.isMethod();
array.property.isEnumerable();
array.property.isReadOnly();
array.property.allowsNonUnique();
array.property.getParent();
*/
/* MOB -- should we have an API that takes a EjsCopyDepth */
extern void ejsSetReturnValue(Ejs *ejs, EjsVar *vp);
extern void ejsSetReturnValueAndFree(Ejs *ejs, EjsVar *vp);
extern void ejsSetReturnValueToBoolean(Ejs *ejs, bool value);
extern void ejsSetReturnValueToBinaryString(Ejs *ejs,
const uchar *value, int len);
extern void ejsSetReturnValueToInteger(Ejs *ejs, int value);
extern void ejsSetReturnValueToNumber(Ejs *ejs, EjsNum value);
extern void ejsSetReturnValueToString(Ejs *ejs, const char *value);
extern void ejsSetReturnValueToUndefined(Ejs *ejs);
/*
* Variable access and control. The fullName arg can contain "[]" and "."
*/
extern bool ejsGetBool(Ejs *ejs, const char *fullName, bool defaultValue);
extern int ejsGetInt(Ejs *ejs, const char *fullName, int defaultValue);
extern const char *ejsGetStr(Ejs *ejs, const char *fullName,
const char *defaultValue);
extern EjsVar *ejsGetVar(Ejs *ejs, const char *fullName);
extern int ejsSetBool(Ejs *ejs, const char *fullName, bool value);
extern int ejsSetInt(Ejs *ejs, const char *fullName, int value);
extern int ejsSetStr(Ejs *ejs, const char *fullName, const char *value);
extern int ejsSetVar(Ejs *ejs, const char *fullName, const EjsVar *value);
extern int ejsSetVarAndFree(Ejs *ejs, const char *fullName, EjsVar *value);
extern int ejsDeleteVar(Ejs *ejs, const char *fullName);
/*
* Error handling
*/
extern void ejsError(Ejs *ejs, const char *errorType, const char *fmt,
...) PRINTF_ATTRIBUTE(3,4);
/* MOB -- this should take no arguments */
extern void ejsArgError(Ejs *ejs, const char *msg);
extern void ejsInternalError(Ejs *ejs, const char *msg);
extern void ejsMemoryError(Ejs *ejs);
extern void ejsSyntaxError(Ejs *ejs, const char *msg);
/*
* Utility methods
*/
extern int ejsParseArgs(int argc, char **argv, const char *fmt, ...);
extern void ejsExit(Ejs *ejs, int status);
extern bool ejsIsExiting(Ejs *ejs);
extern void ejsClearExiting(Ejs *ejs);
extern bool ejsGotException(Ejs *ejs);
/* MOB -- rename Method to Function */
extern void ejsFreeMethodArgs(Ejs *ep, MprArray *args);
extern int ejsStrcat(Ejs *ep, EjsVar *dest, EjsVar *src);
/*
* Debugging routines
*/
extern char *ejsGetErrorMsg(Ejs *ejs);
extern int ejsGetLineNumber(Ejs *ejs);
extern void ejsTrace(Ejs *ejs, const char *fmt, ...);
/*
* Multithreaded lock routines
*/
#if BLD_FEATURE_MULTITHREAD
#define ejsLock(sp) if (sp->lock) { (sp->lock)(sp->lockData); } else
#define ejsUnlock(sp) if (sp->unlock) { (sp->unlock)(sp->lockData); } else
#else
#define ejsLock(sp)
#define ejsUnlock(sp)
#endif
#ifdef __cplusplus
}
#endif
#endif /* _h_EJS */
/*****************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,273 @@
/*
* @file ejsClass.c
* @brief EJS class support
*/
/********************************* Copyright **********************************/
/*
* @copy default
*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
* Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved.
*
* This software is distributed under commercial and open source licenses.
* You may use the GPL open source license described below or you may acquire
* a commercial license from Mbedthis Software. You agree to be fully bound
* by the terms of either license. Consult the LICENSE.TXT distributed with
* this software for full details.
*
* This software is open source; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See the GNU General Public License for more
* details at: http://www.mbedthis.com/downloads/gplLicense.html
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This GPL license does NOT permit incorporating this software into
* proprietary programs. If you are unable to comply with the GPL, you must
* acquire a commercial license to use this software. Commercial licenses
* for this software and support services are available from Mbedthis
* Software at http://www.mbedthis.com
*
* @end
*/
/********************************* Includes ***********************************/
#include "ejs.h"
#if BLD_FEATURE_EJS
/************************************ Code ************************************/
/*
* Internal API
*
* Routine to create a simple class object. This routine will create a
* stand-alone class object. Callers must insert this into the relevant
* "global" object for name resolution. From these class objects, instance
* objects may be created via the javascript "new" command.
*
* Users should use ejsDefineClass
*/
EjsVar *ejsCreateSimpleClass(Ejs *ep, EjsVar *baseClass, const char *className)
{
EjsProperty *pp;
EjsVar *classObj;
/*
* Create an instance of an Object to act as the static class object
*/
classObj = ejsCreateSimpleObjUsingClass(ep, baseClass);
if (classObj == 0) {
mprAssert(classObj);
return 0;
}
ejsSetClassName(ep, classObj, className);
/*
* Set the propotype property to point to this class.
* Note: this is a self reference so the alive bit will not be turned on.
*/
pp = ejsSetProperty(ep, classObj, "prototype", classObj);
ejsMakePropertyEnumerable(pp, 0);
return classObj;
}
/******************************************************************************/
/*
* Define a class in the given interpreter. If parentClass is specified, the
* class is defined in the parent. Otherwise, the class will be defined
* locally/globally. ClassName and extends are full variable specs
* (may contain ".")
*/
EjsVar *ejsDefineClass(Ejs *ep, const char *className, const char *extends,
EjsCMethod constructor)
{
EjsVar *parentClass, *classObj, *baseClass, *vp;
char *name;
char *cp;
/*
* If the className is a qualified name (with "."), then get the
* parent class name.
*/
name = mprStrdup(ep, className);
cp = strrchr(name, '.');
if (cp != 0) {
*cp++ = '\0';
className = cp;
parentClass = ejsFindProperty(ep, 0, 0, ep->global, ep->local, name, 0);
if (parentClass == 0 || parentClass->type != EJS_TYPE_OBJECT) {
mprError(ep, MPR_LOC, "Can't find class's parent class %s", name);
mprFree(name);
return 0;
}
} else {
/*
* Simple class name without a "." so create the class locally
* if a local scope exists, otherwise globally.
*/
parentClass = (ep->local) ? ep->local : ep->global;
}
if (parentClass == 0) {
mprError(ep, MPR_LOC, "Can't find parent class");
mprFree(name);
return 0;
}
/* OPT should use function that doesn't parse [] . */
baseClass = ejsGetClass(ep, 0, extends);
if (baseClass == 0) {
mprAssert(baseClass);
mprFree(name);
return 0;
}
classObj = ejsCreateSimpleClass(ep, baseClass, className);
if (classObj == 0) {
mprAssert(classObj);
mprFree(name);
return 0;
}
if (constructor) {
ejsDefineCMethod(ep, classObj, className, constructor, 0);
}
ejsSetPropertyAndFree(ep, parentClass, className, classObj);
vp = ejsGetPropertyAsVar(ep, parentClass, className);
mprFree(name);
return vp;
}
/******************************************************************************/
/*
* Find a class and return the property defining the class. ClassName may
* contain "." and is interpreted relative to obj. Obj is typically some
* parent object, ep->local or ep->global. If obj is null, then the global
* space is used.
*/
EjsVar *ejsGetClass(Ejs *ep, EjsVar *obj, const char *className)
{
EjsVar *vp;
mprAssert(ep);
/*
* Search first for a constructor of the name of class
* global may not be defined yet.
*/
if (obj) {
vp = ejsFindProperty(ep, 0, 0, obj, 0, className, 0);
} else {
mprAssert(ep->global);
vp = ejsFindProperty(ep, 0, 0, ep->global, ep->local, className, 0);
}
if (vp == 0 || vp->type != EJS_TYPE_OBJECT) {
return 0;
}
/*
* Return a reference to the prototype (self) reference. This
* ensures that even if "obj" is deleted, this reference will remain
* usable.
*/
return ejsGetPropertyAsVar(ep, vp, "prototype");
}
/******************************************************************************/
/*
* Return the class name of a class or object
*/
const char *ejsGetClassName(EjsVar *vp)
{
EjsObj *obj;
mprAssert(vp);
mprAssert(vp->type == EJS_TYPE_OBJECT);
mprAssert(vp->objectState->baseClass);
if (vp == 0 || !ejsVarIsObject(vp)) {
return 0;
}
obj = vp->objectState;
return obj->className;
}
/******************************************************************************/
/*
* Return the class name of an objects underlying class
* If called on an object, it returns the base class.
* If called on a class, it returns the base class for the class.
*/
const char *ejsGetBaseClassName(EjsVar *vp)
{
EjsObj *obj;
mprAssert(vp);
mprAssert(vp->type == EJS_TYPE_OBJECT);
mprAssert(vp->objectState->baseClass);
if (vp == 0 || !ejsVarIsObject(vp)) {
return 0;
}
obj = vp->objectState;
if (obj->baseClass == 0) {
return 0;
}
mprAssert(obj->baseClass->objectState);
return obj->baseClass->objectState->className;
}
/******************************************************************************/
EjsVar *ejsGetBaseClass(EjsVar *vp)
{
if (vp == 0 || !ejsVarIsObject(vp) || vp->objectState == 0) {
mprAssert(0);
return 0;
}
return vp->objectState->baseClass;
}
/******************************************************************************/
void ejsSetBaseClass(EjsVar *vp, EjsVar *baseClass)
{
if (vp == 0 || !ejsVarIsObject(vp) || vp->objectState == 0) {
mprAssert(0);
return;
}
vp->objectState->baseClass = baseClass;
}
/******************************************************************************/
#else
void ejsProcsDummy() {}
/******************************************************************************/
#endif /* BLD_FEATURE_EJS */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,468 @@
/*
* @file ejsCmd.c
* @brief Embedded JavaScript (EJS) command line program.
* @overview
*/
/********************************* Copyright **********************************/
/*
* @copy default
*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
* Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved.
*
* This software is distributed under commercial and open source licenses.
* You may use the GPL open source license described below or you may acquire
* a commercial license from Mbedthis Software. You agree to be fully bound
* by the terms of either license. Consult the LICENSE.TXT distributed with
* this software for full details.
*
* This software is open source; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See the GNU General Public License for more
* details at: http://www.mbedthis.com/downloads/gplLicense.html
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This GPL license does NOT permit incorporating this software into
* proprietary programs. If you are unable to comply with the GPL, you must
* acquire a commercial license to use this software. Commercial licenses
* for this software and support services are available from Mbedthis
* Software at http://www.mbedthis.com
*
* @end
*/
/********************************** Includes **********************************/
#include "ejs.h"
#if BLD_FEATURE_EJS && !BREW
/************************************ Defines *********************************/
#define EJS_MAX_CMD_LINE (16 * 1024)
#define EJS_MAX_SCRIPT (4 * 1024 * 1024)
#define EJS_MAX_RESULT_SIZE (4 * 1024 * 1024)
#define EJS_PROMPT "ejs> "
/****************************** Forward Declarations **************************/
static int parseFile(EjsService *ejsService, Ejs *ejs, const char *fileName,
const char *testName, MprFile *testLogFile);
static int ifConsole();
static int interactiveUse(MprApp *app, Ejs *ejs, FILE *input,
char *fileName);
static char *readCmd(MprApp *app, FILE *input);
static int memoryFailure(MprApp *app, uint size, uint total, bool granted);
static int isConsole = 0;
static int traceCmds = 0;
static int stats = 0;
static int verbose = 0;
/************************************ Main ************************************/
int main(int argc, char *argv[])
{
MprApp *app;
const char *programName;
MprFile *testLogFile;
EjsService *ejsService;
Ejs *ejs;
char *commandLine;
const char *testName;
char *argp, *cmd, *testLog;
int i, rc, nextArg, err, len, firstArg, iterations, debugLevel;
app = mprInit(memoryFailure);
isConsole = ifConsole();
programName = mprGetBaseName(argv[0]);
debugLevel = 0;
ejsService = ejsOpenService(app);
if (ejsService == 0) {
mprError(app, MPR_LOC, "Can't initialize the EJS service.");
return -1;
}
err = 0;
iterations = 1;
stats = 0;
testLog = getenv("TEST_LOG");
testLogFile = 0;
testName = 0;
for (nextArg = 1; nextArg < argc; nextArg++) {
argp = argv[nextArg];
if (*argp != '-') {
break;
}
if (strcmp(argp, "--debug") == 0) {
if (nextArg >= argc) {
err++;
} else {
debugLevel = atoi(argv[++nextArg]);
}
} else if (strcmp(argp, "--stats") == 0) {
stats++;
} else if (strcmp(argp, "--trace") == 0) {
traceCmds++;
} else if (strcmp(argp, "--iterations") == 0) {
if (nextArg >= argc) {
err++;
} else {
iterations = atoi(argv[++nextArg]);
}
} else if (strcmp(argp, "--log") == 0) {
/* Get file to log test results to when using ejs as a test shell */
if (nextArg >= argc) {
err++;
} else {
testLog = argv[++nextArg];
}
} else if (strcmp(argp, "--testName") == 0) {
if (nextArg >= argc) {
err++;
} else {
testName = argv[++nextArg];
}
} else if (strcmp(argp, "-v") == 0) {
verbose++;
} else if (strcmp(argp, "-vv") == 0) {
verbose += 2;
} else if (strcmp(argp, "--verbose") == 0) {
verbose += 2;
} else {
err++;
break;
}
if (err) {
mprErrorPrintf(app,
"Usage: %s [options] files... or\n"
" %s < file or\n"
" %s or\n"
" Switches:\n"
" --iterations num # Number of iterations to eval file\n"
" --stats # Output stats on exit\n"
" --testName name # Set the test name",
programName, programName, programName);
return -1;
}
}
if (testName) {
i = 0;
commandLine = 0;
len = mprAllocStrcat(MPR_LOC_ARGS(app), &commandLine, 0, " ",
mprGetBaseName(argv[i++]), 0);
for (; i < argc; i++) {
len = mprReallocStrcat(MPR_LOC_ARGS(app), &commandLine, 0, len,
" ", argv[i], 0);
}
mprPrintf(app, " %s\n", commandLine);
}
if (testLog) {
testLogFile = mprOpen(app, testLog,
O_CREAT | O_APPEND | O_WRONLY | O_TEXT, 0664);
if (testLogFile == 0) {
mprError(app, MPR_LOC, "Can't open %s", testLog);
return MPR_ERR_CANT_OPEN;
}
mprFprintf(testLogFile, "\n %s\n", commandLine);
}
ejs = ejsCreateInterp(ejsService, 0, 0, 0, 0);
if (ejs == 0) {
mprError(app, MPR_LOC, "Can't create EJS interpreter");
ejsCloseService(ejsService, stats);
if (testLogFile) {
mprClose(testLogFile);
}
mprTerm(app, stats);
exit(-1);
}
if (debugLevel > 0) {
ejsSetGCDebugLevel(ejs, debugLevel);
}
rc = 0;
if (nextArg < argc) {
/*
* Process files supplied on the command line
*/
firstArg = nextArg;
for (i = 0; i < iterations; i++) {
for (nextArg = firstArg; nextArg < argc; nextArg++) {
rc = parseFile(ejsService, ejs, argv[nextArg], testName,
testLogFile);
if (rc < 0) {
return rc;
}
}
}
if (testName) {
if (verbose == 1) {
mprPrintf(app, "\n");
}
if (verbose <= 1) {
mprPrintf(app, " # PASSED all tests for \"%s\"\n", testName);
}
}
} else if (! isConsole) {
/*
* Read a script from stdin
*/
cmd = readCmd(app, stdin);
ejsSetFileName(ejs, "stdin");
rc = ejsEvalScript(ejs, cmd, 0);
if (rc < 0) {
mprPrintf(app, "ejs: Error: %s\n", ejsGetErrorMsg(ejs));
}
mprFree(cmd);
} else {
/*
* Interactive use. Read commands from the command line.
*/
rc = interactiveUse(app, ejs, stdin, "stdin");
}
/*
* Cleanup. Do stats if required.
*/
if (ejs) {
ejsCleanInterp(ejs, 0);
ejsCleanInterp(ejs->service->master, 0);
ejsDestroyInterp(ejs, 0);
}
ejsCloseService(ejsService, stats);
if (testLogFile) {
mprClose(testLogFile);
}
mprTerm(app, stats);
return rc;
}
/******************************************************************************/
static int parseFile(EjsService *ejsService, Ejs *ejs, const char *fileName,
const char *testName, MprFile *testLogFile)
{
int rc;
if (testName && verbose == 1) {
mprPrintf(ejs, ".");
}
if (verbose > 1) {
mprPrintf(ejs, "File: %s\n", fileName);
}
rc = ejsEvalFile(ejs, fileName, 0);
if (testName) {
char fileBuf[MPR_MAX_FNAME], *cp;
mprStrcpy(fileBuf, sizeof(fileBuf), fileName);
if ((cp = strstr(fileBuf, ".ejs")) != 0) {
*cp = '\0';
}
if (rc == 0) {
if (verbose > 1) {
mprPrintf(ejs, " # PASSED test \"%s.%s\"\n", testName,
fileBuf);
}
if (testLogFile) {
mprFprintf(testLogFile, " # PASSED test \"%s.%s\"\n",
testName, fileBuf);
}
} else {
mprPrintf(ejs, "FAILED test \"%s.%s\"\nDetails: %s\n",
testName, fileBuf, ejsGetErrorMsg(ejs));
if (testLogFile) {
mprFprintf(testLogFile,
"FAILED test \"%s.%s\"\nDetails: %s\n",
testName, fileBuf, ejsGetErrorMsg(ejs));
}
}
} else if (rc < 0) {
mprPrintf(ejs, "ejs: %sIn file \"%s\"\n",
ejsGetErrorMsg(ejs), fileName);
}
return rc;
}
/******************************************************************************/
static char *readCmd(MprApp *app, FILE *input)
{
char line[EJS_MAX_CMD_LINE];
char *cmd;
int len, cmdLen;
cmd = 0;
cmdLen = 0;
line[sizeof(line) - 1] = '\0';
while (1) {
if (fgets(line, sizeof(line) - 1, input) == NULL) {
break;
}
len = strlen(line);
if (line[len - 1] == '\\') {
line[len - 1] = '\0';
}
cmdLen = mprReallocStrcat(MPR_LOC_ARGS(app), &cmd, EJS_MAX_SCRIPT,
cmdLen, 0, line, 0);
}
return cmd;
}
/******************************************************************************/
static int interactiveUse(MprApp *app, Ejs *ejs, FILE *input, char *fileName)
{
EjsVar result;
char line[EJS_MAX_CMD_LINE];
char *cmd, *buf;
int len, cmdLen, rc;
cmd = 0;
cmdLen = 0;
line[sizeof(line) - 1] = '\0';
ejsSetFileName(ejs, "console");
while (! ejsIsExiting(ejs)) {
if (isConsole) {
write(1, EJS_PROMPT, strlen(EJS_PROMPT));
}
if (fgets(line, sizeof(line) - 1, input) == NULL) {
break;
}
len = strlen(line);
while (len > 0 &&
(line[len - 1] == '\n' || line[len - 1] == '\r')) {
len--;
line[len] = '\0';
}
if (line[len - 1] == '\\') {
line[len - 1] = '\0';
cmdLen = mprReallocStrcat(MPR_LOC_ARGS(app), &cmd, EJS_MAX_SCRIPT,
cmdLen, 0, line, 0);
} else {
cmdLen = mprReallocStrcat(MPR_LOC_ARGS(app), &cmd, EJS_MAX_SCRIPT,
cmdLen, 0, line, 0);
if (traceCmds) {
mprPrintf(ejs, "# %s\n", cmd);
}
if (cmd[0] == 0x4 || cmd[0] == 0x26 || strcmp(cmd, "quit") == 0) {
ejsExit(ejs, 0);
} else if ((rc = ejsEvalScript(ejs, cmd, &result)) < 0) {
mprPrintf(app, "ejs: Error: %s\n", ejsGetErrorMsg(ejs));
if (! isConsole) {
return rc;
}
} else {
if (isConsole || traceCmds) {
buf = ejsVarToString(ejs, &result);
mprPrintf(ejs, "%s\n", buf);
}
}
mprFree(cmd);
cmd = 0;
cmdLen = 0;
}
}
return 0;
}
/******************************************************************************/
static int ifConsole()
{
#if WIN
INPUT_RECORD irec[1];
int records = 0;
if (PeekConsoleInput(GetStdHandle(STD_INPUT_HANDLE), irec, 1,
&records) != 0) {
return 1;
}
#else
return isatty(0);
#endif
return 0;
}
/******************************************************************************/
static int memoryFailure(MprApp *app, uint size, uint total, bool granted)
{
if (!granted) {
mprPrintf(app, "Can't allocate memory block of size %d\n", size);
mprPrintf(app, "Total memory used %d\n", total);
exit(255);
}
mprPrintf(app, "Memory request for %d bytes exceeds memory red-line\n",
size);
mprPrintf(app, "Total memory used %d\n", total);
return 0;
}
/******************************************************************************/
#else
void ejsCmdLineDummy() {}
/******************************************************************************/
#endif /* BLD_FEATURE_EJS */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,141 @@
/*
* @file event.js
* @brief Event class
* @copy Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*
* Usage:
* listener = new System.Listener();
* listener.onClick = function() {
* // Any code here
* }
* eventTarget.addListener(eventName, listener);
* or
* listener = new System.Listener(obj, method);
* eventTarget.addListener(eventName, listener);
*
* To fire events:
* eventTarget.fire(eventName, new System.Event("My Event"));
*/
/******************************************************************************/
/*
* Base event class
*/
class System.Event
{
var type; // keyboard
var timeStamp;
var arg;
/* MOB -- constructor should take a type */
function Event(arg)
{
timeStamp = time();
type = "default";
this.arg = arg;
}
}
/* MOB -- should not be needed */
Event = System.Event;
class System.Listener
{
var obj;
var method;
function Listener(obj, method)
{
if (arguments.length >= 1) {
this.obj = obj;
} else {
this.obj = this;
}
if (arguments.length == 2) {
this.method = method;
} else {
this.method = "onEvent";
}
}
}
/* MOB -- should not be needed */
Listener = System.Listener;
/*
* The Event target class
*/
class System.EventTarget
{
// Private
var events; /* Hash of a event names */
function EventTarget()
{
events = new Object();
}
// Public
function addListener(eventName, listener)
{
var listeners = events[eventName];
if (listeners == undefined) {
listeners = events[eventName] = new Array();
}
if (arguments.length == 2) {
var method = eventName;
}
/* MOB OPT */
for (var i = 0; i < listeners.length; i++) {
var l = listeners[i];
if (l == listener) {
return;
}
}
listeners[listeners.length] = listener;
}
function removeListener(eventName, listener)
{
var listeners = events[eventName];
if (listeners == undefined) {
return;
}
for (var i = 0; i < listeners.length; i++) {
var l = listeners[i];
if (l == listener) {
// MOB -- want listeners.splice here
// listeners.splice(i, 1);
for (var j = i; j < (listeners.length - 1); j++) {
listeners[j] = listeners[j + 1];
}
delete listeners[listeners.length - 1];
i = listeners.length;
}
}
}
function fire(eventName, event)
{
var listeners = events[eventName];
if (listeners == undefined) {
// println("Event.fire(): unknown eventName " + eventName);
return;
}
for (var i = listeners.length - 1; i >= 0; i--) {
var listener = listeners[i];
var method = listener.obj[listener.method];
if (method == undefined) {
throw new EvalError("Undefined method: " + listener.method);
}
listener.obj[listener.method](listener, event);
}
}
}
/* MOB -- should not be needed */
EventTarget = System.EventTarget;
@@ -0,0 +1,34 @@
/*
* @file global.js
* @brief Misc global functions
* @copy Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*/
/******************************************************************************/
function min(a, b)
{
if (a < b) {
return a;
} else {
return b;
}
}
function max(a, b)
{
if (a > b) {
return a;
} else {
return b;
}
}
function abs(a)
{
if (a < 0) {
return -a;
}
return a;
}
@@ -0,0 +1,15 @@
/*
* @file startup.js
* @brief Embedded JavaScript Startup Code
* @copy Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*
* Invoked automatically on startup.
*/
/******************************************************************************/
// println("Loading startup.js ...");
include("lib/event.js");
include("lib/global.js");
include("lib/timer.js");
@@ -0,0 +1,158 @@
/*
* @file timer.js
* @brief Timer class
* @copy Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*
* Usage:
* timer = new System.Timer("name", period);
* timer.onTick = function(arg) {
* // Anything here
* }
* timer.start();
* or
*
* timer = new System.Timer("name", period, obj, method);
* timer.start();
*/
/******************************************************************************/
class System.Timer
{
var id;
/* MOB -- really need accessor on period. If user updates period,
then due must be updated. */
var period;
var due;
var runOnce; // Run timer just once
var method; // Callback method
var obj; // Callback object
function Timer(id, period, obj, method)
{
this.id = id;
this.period = period;
due = time() + period;
if (arguments.length >= 3) {
this.obj = obj;
} else {
this.obj = this;
}
if (arguments.length >= 4) {
this.method = method;
} else {
this.method = "onTick";
}
}
/* MOB this should be deprecated */
function reschedule(period)
{
/* MOB -- should update the timer service somehow */
this.period = period;
}
function run(now)
{
if (obj[method] == undefined) {
trace("Timer cant find timer method " + method);
due = now + this.period;
return;
}
/*
* Run the timer
*/
try {
obj[method](this);
}
catch (error) {
trace("Timer exception: " + error);
}
if (runOnce) {
timerService.removeTimer(this);
} else {
due = now + this.period;
}
}
function start()
{
if (obj[method] == undefined) {
throw new Error("Callback method is undefined");
} else {
timerService.addTimer(this);
}
}
function stop()
{
timerService.removeTimer(this);
}
}
/* MOB -- should not need this */
Timer = System.Timer;
/*
* Timer service
*/
class System.TimerService
{
var timers;
var nextDue;
function TimerService()
{
timers = new Object();
nextDue = 0;
global.timerService = this;
}
function addTimer(timer)
{
timers[timer.id] = timer;
}
function removeTimer(timer)
{
try {
delete timers[timer.id];
}
catch {}
}
function getIdleTime()
{
return nextDue - time();
}
function runTimers()
{
var now = time();
nextDue = 2147483647; /* MOB -- MATH.MAX_INT; */
for each (var timer in timers)
{
if (timer.due < now) {
timer.run(now);
}
}
for each (var timer in timers)
{
if (timer.due < nextDue) {
nextDue = timer.due;
}
}
// println("runTimers leaving with " + (nextDue - now));
return nextDue - time();
}
}
TimerService = System.TimerService;
+1
View File
@@ -0,0 +1 @@
.updated
+27
View File
@@ -0,0 +1,27 @@
#
# Makefile to build the EJS Object Model
#
# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
#
COMPILE := *.c
EXPORT_OBJECTS := yes
MAKE_IFLAGS := -I.. -I../../mpr -I../../exml
include make.dep
ifeq ($(BLD_HOST_UNIX),1)
PRE_DIRS = UNIX
else
PRE_DIRS = $(BLD_HOST_OS)
endif
compileExtra: .updated
.updated: $(FILES)
@touch .updated
## Local variables:
## tab-width: 4
## End:
## vim: tw=78 sw=4 ts=4
@@ -0,0 +1,63 @@
Embedded JavaScript System Model
- Need args, arg types and exceptions thrown
- Error classes
class Global
class System
class environment
var
class GC
void function run()
function tune()
function getUsedMemory() // Should be properties
function getAllocatedMemory() // Should be properties
var javascript
var null
var undefined
var true
var false
var Nan
var Infinity
function random // Not implemented
function sleep // Not implemented
function exit
function yield // Not implemented
Debug
isDebugMode
Limits
isLimitsMode // Not implemented
stack // Not implemented
heap // Not implemented
flash // Not implemented
Memory
getUsedMemory() // Should be properties
getAvailableMemory() // Should be properties
used
flash // Not implemented
assert()
breakpoint()
dirname()
basename()
eval()
exit()
print()
println()
printVars()
sleep()
sort()
time()
typeof()
include()
trace()
printf() // Not implemented
sprintf()
@@ -0,0 +1 @@
.updated
+21
View File
@@ -0,0 +1,21 @@
#
# Makefile to build the EJS Object Model for WIN
#
# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
#
COMPILE := *.c
EXPORT_OBJECTS := yes
MAKE_IFLAGS := -I../.. -I../../../mpr
include make.dep
compileExtra: .updated
.updated: $(FILES)
@touch .updated
## Local variables:
## tab-width: 4
## End:
## vim: tw=78 sw=4 ts=4
@@ -0,0 +1,98 @@
/*
* @file ejsFile.c
* @brief File class for the EJ System Object Model
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
/******************************************************************************/
/*
* Default Constructor
*/
/******************************************************************************/
/************************************ Methods *********************************/
/******************************************************************************/
/*
* function open();
*/
static int openProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "File.open()\n");
return 0;
}
/******************************************************************************/
/*
* function close();
*/
static int closeProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "File.close()\n");
return 0;
}
/******************************************************************************/
/*
* function read();
*/
static int readProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "File.read()\n");
return 0;
}
/******************************************************************************/
/*
* function write();
*/
static int writeProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "File.write()\n");
return 0;
}
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineFileClass(Ejs *ep)
{
EjsVar *fileClass;
fileClass = ejsDefineClass(ep, "File", "Object", 0);
if (fileClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
/*
* Define the methods
*/
ejsDefineCMethod(ep, fileClass, "open", openProc, 0);
ejsDefineCMethod(ep, fileClass, "close", closeProc, 0);
ejsDefineCMethod(ep, fileClass, "read", readProc, 0);
ejsDefineCMethod(ep, fileClass, "write", writeProc, 0);
return ejsObjHasErrors(fileClass) ? MPR_ERR_CANT_INITIALIZE: 0;
}
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,454 @@
/*
* @file ejsFileSystem.c
* @brief FileSystem class for the EJ System Object Model
* MOB -- this is almost the same as for Windows. Should common up.
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
#include <dirent.h>
/******************************************************************************/
/************************************ Methods *********************************/
/******************************************************************************/
/*
* function void access(string path);
* MOB - API insufficient. Access for read or write?
*/
static int accessProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
int rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: access(path)");
return -1;
}
rc = access(argv[0]->string, 04);
ejsSetReturnValueToBoolean(ejs, (rc == 0) ? 1 : 0);
return 0;
}
/******************************************************************************/
/*
* function void mkdir(string path);
*/
static int mkdirProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: mkdir(path)");
return -1;
}
if (mprMakeDirPath(ejs, argv[0]->string) < 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant create directory");
return -1;
}
return 0;
}
/******************************************************************************/
/*
* function void rmdir(string path);
*/
static int rmdirProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
int rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: mkdir(path)");
return -1;
}
rc = mprDeleteDir(ejs, argv[0]->string);
if (rc < 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant remove directory");
return -1;
}
return 0;
}
/******************************************************************************/
/*
* function void dirList(string path, [bool enumDirs]);
* MOB -- need pattern to match (what about "." and ".." and ".*"
*/
static int dirListProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
DIR *dir;
struct dirent *dirent;
char path[MPR_MAX_FNAME];
EjsVar *array, *vp;
uchar enumDirs;
if (argc < 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: dirList(path)");
return -1;
}
if (argc == 2) {
enumDirs = ejsVarToBoolean(argv[1]);
} else {
enumDirs = 0;
}
array = ejsCreateArray(ejs, 0);
ejsMakeObjPermanent(array, 1);
/*
* First collect the files
*/
mprSprintf(path, sizeof(path), "%s/*.*", argv[0]->string);
dir = opendir(path);
if (dir == 0) {
ejsError(ejs, EJS_ARG_ERROR, "Can't enumerate dirList(path)");
return -1;
}
while ((dirent = readdir(dir)) != 0) {
if (dirent->d_name[0] == '.') {
continue;
}
if (!enumDirs || (dirent->d_type & DT_DIR)) {
mprSprintf(path, sizeof(path), "%s/%s", argv[0]->string,
dirent->d_name);
vp = ejsCreateStringVar(ejs, path);
ejsAddArrayElt(ejs, array, vp, EJS_SHALLOW_COPY);
ejsFreeVar(ejs, vp);
}
}
closedir(dir);
ejsSetReturnValue(ejs, array);
ejsMakeObjPermanent(array, 0);
/*
* Can free now as the return value holds the reference
*/
ejsFreeVar(ejs, array);
return 0;
}
/******************************************************************************/
/*
* function void getFreeSpace();
*/
static int getFreeSpaceProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
#if UNUSED
MprApp *app;
uint space;
app = mprGetApp(ejs);
space = IFILEMGR_GetFreeSpace(app->fileMgr, 0);
ejsSetReturnValueToInteger(ejs, space);
#endif
return 0;
}
/******************************************************************************/
/*
* function void writeFile(string path, var data);
*/
static int writeFileProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
MprFile *file;
char *data, *buf;
int bytes, length, rc;
if (argc != 2 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: writeFile(path, var)");
return -1;
}
if (ejsVarIsString(argv[1])) {
data = argv[1]->string;
length = argv[1]->length;
buf = 0;
} else {
buf = data = ejsVarToString(ejs, argv[1]);
length = strlen(data);
}
/*
* Create fails if already present
*/
rc = mprDelete(ejs, argv[0]->string);
file = mprOpen(ejs, argv[0]->string, O_CREAT | O_WRONLY | O_BINARY, 0664);
if (file == 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant create %s", argv[0]->string);
mprFree(buf);
return -1;
}
rc = 0;
bytes = mprWrite(file, data, length);
if (bytes != length) {
ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string);
rc = -1;
}
mprClose(file);
mprFree(buf);
return rc;
}
/******************************************************************************/
/*
* function string readFile(string path);
*/
static int readFileProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
MprApp *app;
MprFile *file;
MprBuf *buf;
char *data;
int bytes, rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: readFile(path)");
return -1;
}
buf = mprCreateBuf(ejs, MPR_BUF_INCR, MPR_MAX_BUF);
if (buf == 0) {
ejsMemoryError(ejs);
return -1;
}
data = mprAlloc(ejs, MPR_BUFSIZE);
if (buf == 0) {
mprFree(buf);
ejsMemoryError(ejs);
return -1;
}
app = mprGetApp(ejs);
file = mprOpen(ejs, argv[0]->string, O_RDONLY, 0664);
if (file == 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant open %s", argv[0]->string);
mprFree(buf);
return -1;
}
rc = 0;
while ((bytes = mprRead(file, data, MPR_BUFSIZE)) > 0) {
if (mprPutBlockToBuf(buf, data, bytes) != bytes) {
ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string);
rc = -1;
break;
}
}
ejsSetReturnValueToBinaryString(ejs, (uchar*) mprGetBufStart(buf),
mprGetBufLength(buf));
mprClose(file);
mprFree(data);
mprFree(buf);
return rc;
}
/******************************************************************************/
/*
* function void remove(string path);
*/
static int removeProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
int rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: remove(path)");
return -1;
}
rc = unlink(argv[0]->string);
if (rc < 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant remove file");
return -1;
}
return 0;
}
/******************************************************************************/
/*
* function void rename(string from, string to);
*/
static int renameProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
int rc;
if (argc != 2 || !ejsVarIsString(argv[0]) || !ejsVarIsString(argv[1])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: rename(old, new)");
return -1;
}
unlink(argv[1]->string);
rc = rename(argv[0]->string, argv[1]->string);
if (rc < 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant rename file");
return -1;
}
return 0;
}
/******************************************************************************/
/*
* function void copy(string old, string new);
*/
static int copyProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
MprFile *from, *to;
char *buf;
uint bytes;
int rc;
if (argc != 2 || !ejsVarIsString(argv[0]) || !ejsVarIsString(argv[1])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: copy(old, new)");
return -1;
}
buf = mprAlloc(ejs, MPR_BUFSIZE);
if (buf == 0) {
ejsMemoryError(ejs);
return -1;
}
from = mprOpen(ejs, argv[0]->string, O_RDONLY | O_BINARY, 0664);
if (from == 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant open %s", argv[0]->string);
mprFree(buf);
return -1;
}
to = mprOpen(ejs, argv[1]->string, O_CREAT | O_BINARY, 0664);
if (to == 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant create %s", argv[1]->string);
mprClose(from);
mprFree(buf);
return -1;
}
rc = 0;
while ((bytes = mprRead(from, buf, MPR_BUFSIZE)) > 0) {
if (mprWrite(to, buf, bytes) != bytes) {
ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string);
rc = -1;
break;
}
}
mprClose(from);
mprClose(to);
mprFree(buf);
return rc;
}
/******************************************************************************/
/*
* function FileInfo getFileInfo(string path);
*
* MOB -- should create a real class FileInfo
*/
static int getFileInfoProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
MprFileInfo info;
EjsVar *fileInfo;
int rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: getFileInfo(path)");
return -1;
}
fileInfo = ejsCreateObjVar(ejs);
if (fileInfo == 0) {
ejsMemoryError(ejs);
return -1;
}
ejsMakeObjPermanent(fileInfo, 1);
rc = mprGetFileInfo(ejs, argv[0]->string, &info);
if (rc < 0) {
ejsMakeObjPermanent(fileInfo, 0);
ejsFreeVar(ejs, fileInfo);
ejsError(ejs, EJS_IO_ERROR, "Cant get file info for %s",
argv[0]->string);
return -1;
}
ejsSetPropertyToInteger(ejs, fileInfo, "created", info.ctime);
ejsSetPropertyToInteger(ejs, fileInfo, "length", info.size);
ejsSetPropertyToBoolean(ejs, fileInfo, "isDir", info.isDir);
ejsSetReturnValue(ejs, fileInfo);
ejsMakeObjPermanent(fileInfo, 0);
return 0;
}
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineFileSystemClass(Ejs *ejs)
{
EjsVar *fileSystemClass;
fileSystemClass = ejsDefineClass(ejs, "FileSystem", "Object", 0);
if (fileSystemClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
/*
* Define the methods
*/
ejsDefineCMethod(ejs, fileSystemClass, "access", accessProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "mkdir", mkdirProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "rmdir", rmdirProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "dirList", dirListProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "writeFile", writeFileProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "readFile", readFileProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "remove", removeProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "rename", renameProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "copy", copyProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "getFileInfo", getFileInfoProc, 0);
// MOB -- should be a property with accessor
ejsDefineCMethod(ejs, fileSystemClass, "getFreeSpace", getFreeSpaceProc, 0);
return ejsObjHasErrors(fileSystemClass) ? MPR_ERR_CANT_INITIALIZE: 0;
}
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
+488
View File
@@ -0,0 +1,488 @@
/*
* @file ejsHTTP.c
* @brief HTTP class for the EJ System Object Model
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
#if UNUSED
/*********************************** Defines **********************************/
#define EJS_WEB_PROPERTY "-web"
#define EJS_HTTP_PROPERTY "-http"
#define EJS_HTTP_DISPOSED 550
/*
* Control structure for one HTTP request structure
*/
typedef struct HTTPControl {
Ejs *ejs;
IWebResp *webResp;
AEECallback *callback;
MprBuf *buf;
EjsVar *thisObj;
char *url;
MprTime requestStarted;
uint timeout;
} HTTPControl;
/****************************** Forward Declarations **************************/
static void cleanup(HTTPControl *hp);
static int createWeb(Ejs *ejs, EjsVar *thisObj);
static void brewCallback(HTTPControl *hp);
static int httpDestructor(Ejs *ejs, EjsVar *vp);
static void httpCallback(HTTPControl *hp, int responseCode);
static int setCallback(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv);
/******************************************************************************/
/*
* Constructor
*/
int ejsHTTPConstructor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 0 && argc != 2) {
ejsError(ejs, EJS_ARG_ERROR,
"Bad usage: HTTP([obj = this, method = onComplete]);");
return -1;
}
if (createWeb(ejs, thisObj) < 0) {
return -1;
}
setCallback(ejs, thisObj, argc, argv);
return 0;
}
/******************************************************************************/
static int createWeb(Ejs *ejs, EjsVar *thisObj)
{
MprApp *app;
void *web;
app = mprGetApp(ejs);
/*
* Create one instance of IWeb for the entire application. Do it here
* so only widgets that require HTTP incurr the overhead.
*/
web = mprGetKeyValue(ejs, "bpWeb");
if (web == 0) {
if (ISHELL_CreateInstance(app->shell, AEECLSID_WEB, &web) != SUCCESS) {
ejsError(ejs, EJS_IO_ERROR, "Can't create IWEB");
return -1;
}
}
mprSetKeyValue(ejs, "bpWeb", web);
return 0;
}
/******************************************************************************/
/************************************ Methods *********************************/
/******************************************************************************/
/*
* function setCallback(obj, methodString);
*/
static int setCallback(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc >= 1) {
ejsSetProperty(ejs, thisObj, "obj", argv[0]);
} else {
ejsSetProperty(ejs, thisObj, "obj", thisObj);
}
if (argc >= 2) {
ejsSetProperty(ejs, thisObj, "method", argv[1]);
} else {
ejsSetPropertyToString(ejs, thisObj, "method", "onComplete");
}
return 0;
}
/******************************************************************************/
/*
* function fetch();
*/
static int fetchProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
HTTPControl *hp;
EjsProperty *pp;
MprApp *app;
IWeb *web;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: fetch(url)");
return -1;
}
app = mprGetApp(ejs);
web = (IWeb*) mprGetKeyValue(ejs, "bpWeb");
/*
* Web options
*
* WEBOPT_USERAGENT (char*) sets user agent
* WEBOPT_HANDLERDATA (void*)
* WEBOPT_CONNECTTIMEOUT (uint) msec
* WEBOPT_CONTENTLENGTH (long)
* WEBOPT_IDLECONNTIMEOUT (int)
* WEBOPT_ACTIVEXACTIONST (uint) Number of active requests
*
* WEBREQUEST_REDIRECT redirect transparently
*
*/
hp = mprAllocType(ejs, HTTPControl);
if (hp == 0) {
ejsMemoryError(ejs);
return -1;
}
hp->ejs = ejs;
hp->buf = mprCreateBuf(hp, MPR_BUF_INCR, MPR_MAX_BUF);
if (hp->buf == 0) {
mprFree(hp);
ejsMemoryError(ejs);
return -1;
}
/*
* We copy thisObj because we need to preserve both the var and the object.
* We pass the var to brewCallback and so it must persist. The call to
* ejsMakeObjPermanent will stop the GC from collecting the object.
*/
hp->thisObj = ejsDupVar(ejs, thisObj, EJS_SHALLOW_COPY);
ejsSetVarName(ejs, hp->thisObj, "internalHttp");
/*
* Must keep a reference to the http object
*/
ejsMakeObjPermanent(hp->thisObj, 1);
/*
* Make a property so we can access the HTTPControl structure from other
* methods.
*/
pp = ejsSetPropertyToPtr(ejs, thisObj, EJS_HTTP_PROPERTY, hp, 0);
ejsMakePropertyEnumerable(pp, 0);
ejsSetObjDestructor(ejs, hp->thisObj, httpDestructor);
hp->url = mprStrdup(hp, argv[0]->string);
hp->timeout = ejsGetPropertyAsInteger(ejs, thisObj, "timeout");
mprGetTime(hp, &hp->requestStarted);
hp->callback = mprAllocTypeZeroed(hp, AEECallback);
CALLBACK_Init(hp->callback, brewCallback, hp);
hp->webResp = 0;
IWEB_GetResponse(web,
(web, &hp->webResp, hp->callback, hp->url,
WEBOPT_HANDLERDATA, hp,
WEBOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)",
WEBOPT_CONNECTTIMEOUT, hp->timeout,
WEBOPT_COPYOPTS, TRUE,
WEBOPT_CONTENTLENGTH, 0,
WEBOPT_END));
ejsSetPropertyToString(ejs, thisObj, "status", "active");
return 0;
}
/******************************************************************************/
/*
* Called whenver the http object is deleted.
*/
static int httpDestructor(Ejs *ejs, EjsVar *thisObj)
{
HTTPControl *hp;
/*
* If the httpCallback has run, then this property will not exist
*/
hp = ejsGetPropertyAsPtr(ejs, thisObj, EJS_HTTP_PROPERTY);
if (hp) {
cleanup(hp);
}
return 0;
}
/******************************************************************************/
/*
* Stop the request immediately without calling the callback
*/
static int stopProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
HTTPControl *hp;
hp = ejsGetPropertyAsPtr(ejs, thisObj, EJS_HTTP_PROPERTY);
if (hp) {
cleanup(hp);
}
return 0;
}
/******************************************************************************/
/*
* Brew HTTP callback. Invoked for any return data.
*/
static void brewCallback(HTTPControl *hp)
{
Ejs *ejs;
EjsVar *thisObj;
ISource *source;
WebRespInfo *info;
char data[MPR_BUF_INCR];
int bytes;
mprAssert(hp);
mprAssert(hp->webResp);
info = IWEBRESP_GetInfo(hp->webResp);
if (info == 0) {
mprAssert(info);
/* should not happen */
return;
}
ejs = hp->ejs;
thisObj = hp->thisObj;
if (! WEB_ERROR_SUCCEEDED(info->nCode)) {
ejsSetPropertyToString(ejs, thisObj, "status", "error");
httpCallback(hp, info->nCode);
return;
}
if (hp->timeout) {
if (mprGetTimeRemaining(hp, hp->requestStarted, hp->timeout) <= 0) {
ejsSetPropertyToString(ejs, thisObj, "status", "timeout");
httpCallback(hp, 504);
return;
}
}
/*
* Normal success
*/
source = info->pisMessage;
mprAssert(source);
bytes = ISOURCE_Read(source, data, sizeof(data));
switch (bytes) {
case ISOURCE_WAIT: // No data yet
ISOURCE_Readable(source, hp->callback);
break;
case ISOURCE_ERROR:
ejsSetPropertyToString(ejs, thisObj, "status", "error");
httpCallback(hp, info->nCode);
break;
case ISOURCE_END:
mprAddNullToBuf(hp->buf);
ejsSetPropertyToString(ejs, thisObj, "status", "complete");
httpCallback(hp, info->nCode);
break;
default:
if (bytes > 0) {
if (mprPutBlockToBuf(hp->buf, data, bytes) != bytes) {
ejsSetPropertyToString(ejs, thisObj, "status", "partialData");
httpCallback(hp, 500);
}
}
ISOURCE_Readable(source, hp->callback);
break;
}
}
/******************************************************************************/
/*
* Invoke the HTTP completion method
*/
static void httpCallback(HTTPControl *hp, int responseCode)
{
Ejs *ejs;
EjsVar *thisObj, *callbackObj;
MprArray *args;
char *msg;
const char *callbackMethod;
mprAssert(hp);
mprAssert(hp->webResp);
thisObj = hp->thisObj;
ejs = hp->ejs;
ejsSetPropertyToInteger(ejs, thisObj, "responseCode", responseCode);
if (mprGetBufLength(hp->buf) > 0) {
ejsSetPropertyToBinaryString(ejs, thisObj, "responseData",
mprGetBufStart(hp->buf), mprGetBufLength(hp->buf));
}
callbackObj = ejsGetPropertyAsVar(ejs, thisObj, "obj");
callbackMethod = ejsGetPropertyAsString(ejs, thisObj, "method");
if (callbackObj != 0 && callbackMethod != 0) {
args = mprCreateItemArray(ejs, EJS_INC_ARGS, EJS_MAX_ARGS);
mprAddItem(args, ejsDupVar(ejs, hp->thisObj, EJS_SHALLOW_COPY));
if (ejsRunMethod(ejs, callbackObj, callbackMethod, args) < 0) {
msg = ejsGetErrorMsg(ejs);
mprError(ejs, MPR_LOC, "HTTP callback failed. Details: %s", msg);
}
ejsFreeMethodArgs(ejs, args);
} else if (ejsRunMethod(ejs, thisObj, "onComplete", 0) < 0) {
msg = ejsGetErrorMsg(ejs);
mprError(ejs, MPR_LOC, "HTTP onComplete failed. Details: %s", msg);
}
cleanup(hp);
}
/******************************************************************************/
/*
* Cleanup
*/
static void cleanup(HTTPControl *hp)
{
Ejs *ejs;
MprApp *app;
int rc;
mprAssert(hp);
mprAssert(hp->webResp);
ejs = hp->ejs;
if (hp->webResp) {
rc = IWEBRESP_Release(hp->webResp);
// mprAssert(rc == 0);
hp->webResp = 0;
}
if (hp->callback) {
CALLBACK_Cancel(hp->callback);
mprFree(hp->callback);
hp->callback = 0;
}
/*
* Once the property is deleted, then if the destructor runs, it will
* notice that the EJS_HTTP_PROPERTY is undefined.
*/
ejsDeleteProperty(ejs, hp->thisObj, EJS_HTTP_PROPERTY);
/*
* Allow garbage collection to work on thisObj
*/
ejsMakeObjPermanent(hp->thisObj, 0);
ejsFreeVar(ejs, hp->thisObj);
mprFree(hp->buf);
mprFree(hp->url);
mprFree(hp);
app = mprGetApp(ejs);
ISHELL_SendEvent(app->shell, (AEECLSID) app->classId, EVT_USER, 0, 0);
}
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineHTTPClass(Ejs *ejs)
{
EjsVar *httpClass;
httpClass =
ejsDefineClass(ejs, "HTTP", "Object", ejsHTTPConstructor);
if (httpClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
/*
* Define the methods
*/
ejsDefineCMethod(ejs, httpClass, "fetch", fetchProc, 0);
ejsDefineCMethod(ejs, httpClass, "stop", stopProc, 0);
ejsDefineCMethod(ejs, httpClass, "setCallback", setCallback, 0);
#if FUTURE
ejsDefineCMethod(ejs, httpClass, "put", put, 0);
ejsDefineCMethod(ejs, httpClass, "upload", upload, 0);
ejsDefineCMethod(ejs, httpClass, "addUploadFile", addUploadFile, 0);
ejsDefineCMethod(ejs, httpClass, "addPostData", addPostData, 0);
ejsDefineCMethod(ejs, httpClass, "setUserPassword", setUserPassword, 0);
ejsDefineCMethod(ejs, httpClass, "addCookie", addCookie, 0);
#endif
/*
* Define properties
*/
ejsSetPropertyToString(ejs, httpClass, "status", "inactive");
/* This default should come from player.xml */
ejsSetPropertyToInteger(ejs, httpClass, "timeout", 30 * 1000);
ejsSetPropertyToInteger(ejs, httpClass, "responseCode", 0);
return ejsObjHasErrors(httpClass) ? MPR_ERR_CANT_INITIALIZE: 0;
}
/******************************************************************************/
void ejsTermHTTPClass(Ejs *ejs)
{
IWeb *web;
int rc;
web = (IWeb*) mprGetKeyValue(ejs, "bpWeb");
if (web) {
rc = IWEB_Release(web);
mprAssert(rc == 0);
}
}
#endif
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1 @@
.updated
+21
View File
@@ -0,0 +1,21 @@
#
# Makefile to build the EJS Object Model for WIN
#
# Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
#
COMPILE := *.c
EXPORT_OBJECTS := yes
MAKE_IFLAGS := -I../.. -I../../../mpr
include make.dep
compileExtra: .updated
.updated: $(FILES)
@touch .updated
## Local variables:
## tab-width: 4
## End:
## vim: tw=78 sw=4 ts=4
@@ -0,0 +1,98 @@
/*
* @file ejsFile.c
* @brief File class for the EJScript System Object Model
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
/******************************************************************************/
/*
* Default Constructor
*/
/******************************************************************************/
/************************************ Methods *********************************/
/******************************************************************************/
/*
* function open();
*/
static int openProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "File.open()\n");
return 0;
}
/******************************************************************************/
/*
* function close();
*/
static int closeProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "File.close()\n");
return 0;
}
/******************************************************************************/
/*
* function read();
*/
static int readProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "File.read()\n");
return 0;
}
/******************************************************************************/
/*
* function write();
*/
static int writeProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "File.write()\n");
return 0;
}
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineFileClass(Ejs *ep)
{
EjsVar *fileClass;
fileClass = ejsDefineClass(ep, "File", "Object", 0);
if (fileClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
/*
* Define the methods
*/
ejsDefineCMethod(ep, fileClass, "open", openProc, 0);
ejsDefineCMethod(ep, fileClass, "close", closeProc, 0);
ejsDefineCMethod(ep, fileClass, "read", readProc, 0);
ejsDefineCMethod(ep, fileClass, "write", writeProc, 0);
return ejsObjHasErrors(fileClass) ? MPR_ERR_CANT_INITIALIZE: 0;
}
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,456 @@
/*
* @file ejsFileSystem.c
* @brief FileSystem class for the EJ System Object Model
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
/******************************************************************************/
/*
* Default Constructor
*/
/******************************************************************************/
/************************************ Methods *********************************/
/******************************************************************************/
/*
* function void access(string path);
* MOB - API insufficient. Access for read or write?
*/
static int accessProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
int rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: access(path)");
return -1;
}
rc = access(argv[0]->string, 04);
ejsSetReturnValueToBoolean(ejs, (rc == 0) ? 1 : 0);
return 0;
}
/******************************************************************************/
/*
* function void mkdir(string path);
*/
static int mkdirProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: mkdir(path)");
return -1;
}
if (mprMakeDirPath(ejs, argv[0]->string) < 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant create directory");
return -1;
}
return 0;
}
/******************************************************************************/
/*
* function void rmdir(string path);
*/
static int rmdirProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
int rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: mkdir(path)");
return -1;
}
rc = mprDeleteDir(ejs, argv[0]->string);
if (rc < 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant remove directory");
return -1;
}
return 0;
}
/******************************************************************************/
/*
* function void dirList(string path, [bool enumDirs]);
* MOB -- need pattern to match (what about "." and ".." and ".*"
*/
static int dirListProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
WIN32_FIND_DATA findData;
HANDLE h;
char path[MPR_MAX_FNAME];
EjsVar *array, *vp;
uchar enumDirs;
if (argc < 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: dirList(path)");
return -1;
}
if (argc == 2) {
enumDirs = ejsVarToBoolean(argv[1]);
} else {
enumDirs = 0;
}
array = ejsCreateArray(ejs, 0);
ejsMakeObjPermanent(array, 1);
/*
* First collect the files
*/
mprSprintf(path, sizeof(path), "%s/*.*", argv[0]->string);
h = FindFirstFile(path, &findData);
if (h == INVALID_HANDLE_VALUE) {
ejsError(ejs, EJS_ARG_ERROR, "Can't enumerate dirList(path)");
return -1;
}
do {
if (findData.cFileName[0] == '.') {
continue;
}
if (!enumDirs ||
(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
mprSprintf(path, sizeof(path), "%s/%s", argv[0]->string,
findData.cFileName);
vp = ejsCreateStringVar(ejs, path);
ejsAddArrayElt(ejs, array, vp, EJS_SHALLOW_COPY);
ejsFreeVar(ejs, vp);
}
} while (FindNextFile(h, &findData) != 0);
FindClose(h);
ejsSetReturnValue(ejs, array);
ejsMakeObjPermanent(array, 0);
/*
* Can free now as the return value holds the reference
*/
ejsFreeVar(ejs, array);
return 0;
}
/******************************************************************************/
/*
* function void getFreeSpace();
*/
static int getFreeSpaceProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
#if UNUSED
MprApp *app;
uint space;
app = mprGetApp(ejs);
space = IFILEMGR_GetFreeSpace(app->fileMgr, 0);
ejsSetReturnValueToInteger(ejs, space);
#endif
return 0;
}
/******************************************************************************/
/*
* function void writeFile(string path, var data);
*/
static int writeFileProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
MprFile *file;
char *data, *buf;
int bytes, length, rc;
if (argc != 2 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: writeFile(path, var)");
return -1;
}
if (ejsVarIsString(argv[1])) {
data = argv[1]->string;
length = argv[1]->length;
buf = 0;
} else {
buf = data = ejsVarToString(ejs, argv[1]);
length = strlen(data);
}
/*
* Create fails if already present
*/
rc = mprDelete(ejs, argv[0]->string);
file = mprOpen(ejs, argv[0]->string, O_CREAT | O_WRONLY | O_BINARY, 0664);
if (file == 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant create %s", argv[0]->string);
mprFree(buf);
return -1;
}
rc = 0;
bytes = mprWrite(file, data, length);
if (bytes != length) {
ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string);
rc = -1;
}
mprClose(file);
mprFree(buf);
return rc;
}
/******************************************************************************/
/*
* function string readFile(string path);
*/
static int readFileProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
MprApp *app;
MprFile *file;
MprBuf *buf;
char *data;
int bytes, rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: readFile(path)");
return -1;
}
buf = mprCreateBuf(ejs, MPR_BUF_INCR, MPR_MAX_BUF);
if (buf == 0) {
ejsMemoryError(ejs);
return -1;
}
data = mprAlloc(ejs, MPR_BUFSIZE);
if (buf == 0) {
mprFree(buf);
ejsMemoryError(ejs);
return -1;
}
app = mprGetApp(ejs);
file = mprOpen(ejs, argv[0]->string, O_RDONLY, 0664);
if (file == 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant open %s", argv[0]->string);
mprFree(buf);
return -1;
}
rc = 0;
while ((bytes = mprRead(file, data, MPR_BUFSIZE)) > 0) {
if (mprPutBlockToBuf(buf, data, bytes) != bytes) {
ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string);
rc = -1;
break;
}
}
ejsSetReturnValueToBinaryString(ejs, mprGetBufStart(buf),
mprGetBufLength(buf));
mprClose(file);
mprFree(data);
mprFree(buf);
return rc;
}
/******************************************************************************/
/*
* function void remove(string path);
*/
static int removeProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
int rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: remove(path)");
return -1;
}
rc = unlink(argv[0]->string);
if (rc < 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant remove file");
return -1;
}
return 0;
}
/******************************************************************************/
/*
* function void rename(string from, string to);
*/
static int renameProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
int rc;
if (argc != 2 || !ejsVarIsString(argv[0]) || !ejsVarIsString(argv[1])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: rename(old, new)");
return -1;
}
unlink(argv[1]->string);
rc = rename(argv[0]->string, argv[1]->string);
if (rc < 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant rename file");
return -1;
}
return 0;
}
/******************************************************************************/
/*
* function void copy(string old, string new);
*/
static int copyProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
MprFile *from, *to;
char *buf;
int bytes, rc;
if (argc != 2 || !ejsVarIsString(argv[0]) || !ejsVarIsString(argv[1])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: copy(old, new)");
return -1;
}
buf = mprAlloc(ejs, MPR_BUFSIZE);
if (buf == 0) {
ejsMemoryError(ejs);
return -1;
}
from = mprOpen(ejs, argv[0]->string, O_RDONLY | O_BINARY, 0664);
if (from == 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant open %s", argv[0]->string);
mprFree(buf);
return -1;
}
to = mprOpen(ejs, argv[1]->string, O_CREAT | O_BINARY, 0664);
if (to == 0) {
ejsError(ejs, EJS_IO_ERROR, "Cant create %s", argv[1]->string);
mprClose(from);
mprFree(buf);
return -1;
}
rc = 0;
while ((bytes = mprRead(from, buf, MPR_BUFSIZE)) > 0) {
if (mprWrite(to, buf, bytes) != bytes) {
ejsError(ejs, EJS_IO_ERROR, "Write error to %s", argv[1]->string);
rc = -1;
break;
}
}
mprClose(from);
mprClose(to);
mprFree(buf);
return rc;
}
/******************************************************************************/
/*
* function FileInfo getFileInfo(string path);
*
* MOB -- should create a real class FileInfo
*/
static int getFileInfoProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
MprFileInfo info;
EjsVar *fileInfo;
int rc;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: getFileInfo(path)");
return -1;
}
fileInfo = ejsCreateObjVar(ejs);
if (fileInfo == 0) {
ejsMemoryError(ejs);
return -1;
}
ejsMakeObjPermanent(fileInfo, 1);
rc = mprGetFileInfo(ejs, argv[0]->string, &info);
if (rc < 0) {
ejsMakeObjPermanent(fileInfo, 0);
ejsFreeVar(ejs, fileInfo);
ejsError(ejs, EJS_IO_ERROR, "Cant get file info for %s",
argv[0]->string);
return -1;
}
ejsSetPropertyToInteger(ejs, fileInfo, "created", info.ctime);
ejsSetPropertyToInteger(ejs, fileInfo, "length", info.size);
ejsSetPropertyToBoolean(ejs, fileInfo, "isDir", info.isDir);
ejsSetReturnValue(ejs, fileInfo);
ejsMakeObjPermanent(fileInfo, 0);
return 0;
}
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineFileSystemClass(Ejs *ejs)
{
EjsVar *fileSystemClass;
fileSystemClass = ejsDefineClass(ejs, "FileSystem", "Object", 0);
if (fileSystemClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
/*
* Define the methods
*/
ejsDefineCMethod(ejs, fileSystemClass, "access", accessProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "mkdir", mkdirProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "rmdir", rmdirProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "dirList", dirListProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "writeFile", writeFileProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "readFile", readFileProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "remove", removeProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "rename", renameProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "copy", copyProc, 0);
ejsDefineCMethod(ejs, fileSystemClass, "getFileInfo", getFileInfoProc, 0);
// MOB -- should be a property with accessor
ejsDefineCMethod(ejs, fileSystemClass, "getFreeSpace", getFreeSpaceProc, 0);
return ejsObjHasErrors(fileSystemClass) ? MPR_ERR_CANT_INITIALIZE: 0;
}
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
+488
View File
@@ -0,0 +1,488 @@
/*
* @file ejsHTTP.c
* @brief HTTP class for the EJ System Object Model
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
#if UNUSED
/*********************************** Defines **********************************/
#define EJS_WEB_PROPERTY "-web"
#define EJS_HTTP_PROPERTY "-http"
#define EJS_HTTP_DISPOSED 550
/*
* Control structure for one HTTP request structure
*/
typedef struct HTTPControl {
Ejs *ejs;
IWebResp *webResp;
AEECallback *callback;
MprBuf *buf;
EjsVar *thisObj;
char *url;
MprTime requestStarted;
uint timeout;
} HTTPControl;
/****************************** Forward Declarations **************************/
static void cleanup(HTTPControl *hp);
static int createWeb(Ejs *ejs, EjsVar *thisObj);
static void brewCallback(HTTPControl *hp);
static int httpDestructor(Ejs *ejs, EjsVar *vp);
static void httpCallback(HTTPControl *hp, int responseCode);
static int setCallback(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv);
/******************************************************************************/
/*
* Constructor
*/
int ejsHTTPConstructor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 0 && argc != 2) {
ejsError(ejs, EJS_ARG_ERROR,
"Bad usage: HTTP([obj = this, method = onComplete]);");
return -1;
}
if (createWeb(ejs, thisObj) < 0) {
return -1;
}
setCallback(ejs, thisObj, argc, argv);
return 0;
}
/******************************************************************************/
static int createWeb(Ejs *ejs, EjsVar *thisObj)
{
MprApp *app;
void *web;
app = mprGetApp(ejs);
/*
* Create one instance of IWeb for the entire application. Do it here
* so only widgets that require HTTP incurr the overhead.
*/
web = mprGetKeyValue(ejs, "bpWeb");
if (web == 0) {
if (ISHELL_CreateInstance(app->shell, AEECLSID_WEB, &web) != SUCCESS) {
ejsError(ejs, EJS_IO_ERROR, "Can't create IWEB");
return -1;
}
}
mprSetKeyValue(ejs, "bpWeb", web);
return 0;
}
/******************************************************************************/
/************************************ Methods *********************************/
/******************************************************************************/
/*
* function setCallback(obj, methodString);
*/
static int setCallback(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc >= 1) {
ejsSetProperty(ejs, thisObj, "obj", argv[0]);
} else {
ejsSetProperty(ejs, thisObj, "obj", thisObj);
}
if (argc >= 2) {
ejsSetProperty(ejs, thisObj, "method", argv[1]);
} else {
ejsSetPropertyToString(ejs, thisObj, "method", "onComplete");
}
return 0;
}
/******************************************************************************/
/*
* function fetch();
*/
static int fetchProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
HTTPControl *hp;
EjsProperty *pp;
MprApp *app;
IWeb *web;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsError(ejs, EJS_ARG_ERROR, "Bad usage: fetch(url)");
return -1;
}
app = mprGetApp(ejs);
web = (IWeb*) mprGetKeyValue(ejs, "bpWeb");
/*
* Web options
*
* WEBOPT_USERAGENT (char*) sets user agent
* WEBOPT_HANDLERDATA (void*)
* WEBOPT_CONNECTTIMEOUT (uint) msec
* WEBOPT_CONTENTLENGTH (long)
* WEBOPT_IDLECONNTIMEOUT (int)
* WEBOPT_ACTIVEXACTIONST (uint) Number of active requests
*
* WEBREQUEST_REDIRECT redirect transparently
*
*/
hp = mprAllocType(ejs, HTTPControl);
if (hp == 0) {
ejsMemoryError(ejs);
return -1;
}
hp->ejs = ejs;
hp->buf = mprCreateBuf(hp, MPR_BUF_INCR, MPR_MAX_BUF);
if (hp->buf == 0) {
mprFree(hp);
ejsMemoryError(ejs);
return -1;
}
/*
* We copy thisObj because we need to preserve both the var and the object.
* We pass the var to brewCallback and so it must persist. The call to
* ejsMakeObjPermanent will stop the GC from collecting the object.
*/
hp->thisObj = ejsDupVar(ejs, thisObj, EJS_SHALLOW_COPY);
ejsSetVarName(ejs, hp->thisObj, "internalHttp");
/*
* Must keep a reference to the http object
*/
ejsMakeObjPermanent(hp->thisObj, 1);
/*
* Make a property so we can access the HTTPControl structure from other
* methods.
*/
pp = ejsSetPropertyToPtr(ejs, thisObj, EJS_HTTP_PROPERTY, hp, 0);
ejsMakePropertyEnumerable(pp, 0);
ejsSetObjDestructor(ejs, hp->thisObj, httpDestructor);
hp->url = mprStrdup(hp, argv[0]->string);
hp->timeout = ejsGetPropertyAsInteger(ejs, thisObj, "timeout");
mprGetTime(hp, &hp->requestStarted);
hp->callback = mprAllocTypeZeroed(hp, AEECallback);
CALLBACK_Init(hp->callback, brewCallback, hp);
hp->webResp = 0;
IWEB_GetResponse(web,
(web, &hp->webResp, hp->callback, hp->url,
WEBOPT_HANDLERDATA, hp,
WEBOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)",
WEBOPT_CONNECTTIMEOUT, hp->timeout,
WEBOPT_COPYOPTS, TRUE,
WEBOPT_CONTENTLENGTH, 0,
WEBOPT_END));
ejsSetPropertyToString(ejs, thisObj, "status", "active");
return 0;
}
/******************************************************************************/
/*
* Called whenver the http object is deleted.
*/
static int httpDestructor(Ejs *ejs, EjsVar *thisObj)
{
HTTPControl *hp;
/*
* If the httpCallback has run, then this property will not exist
*/
hp = ejsGetPropertyAsPtr(ejs, thisObj, EJS_HTTP_PROPERTY);
if (hp) {
cleanup(hp);
}
return 0;
}
/******************************************************************************/
/*
* Stop the request immediately without calling the callback
*/
static int stopProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
HTTPControl *hp;
hp = ejsGetPropertyAsPtr(ejs, thisObj, EJS_HTTP_PROPERTY);
if (hp) {
cleanup(hp);
}
return 0;
}
/******************************************************************************/
/*
* Brew HTTP callback. Invoked for any return data.
*/
static void brewCallback(HTTPControl *hp)
{
Ejs *ejs;
EjsVar *thisObj;
ISource *source;
WebRespInfo *info;
char data[MPR_BUF_INCR];
int bytes;
mprAssert(hp);
mprAssert(hp->webResp);
info = IWEBRESP_GetInfo(hp->webResp);
if (info == 0) {
mprAssert(info);
/* should not happen */
return;
}
ejs = hp->ejs;
thisObj = hp->thisObj;
if (! WEB_ERROR_SUCCEEDED(info->nCode)) {
ejsSetPropertyToString(ejs, thisObj, "status", "error");
httpCallback(hp, info->nCode);
return;
}
if (hp->timeout) {
if (mprGetTimeRemaining(hp, hp->requestStarted, hp->timeout) <= 0) {
ejsSetPropertyToString(ejs, thisObj, "status", "timeout");
httpCallback(hp, 504);
return;
}
}
/*
* Normal success
*/
source = info->pisMessage;
mprAssert(source);
bytes = ISOURCE_Read(source, data, sizeof(data));
switch (bytes) {
case ISOURCE_WAIT: // No data yet
ISOURCE_Readable(source, hp->callback);
break;
case ISOURCE_ERROR:
ejsSetPropertyToString(ejs, thisObj, "status", "error");
httpCallback(hp, info->nCode);
break;
case ISOURCE_END:
mprAddNullToBuf(hp->buf);
ejsSetPropertyToString(ejs, thisObj, "status", "complete");
httpCallback(hp, info->nCode);
break;
default:
if (bytes > 0) {
if (mprPutBlockToBuf(hp->buf, data, bytes) != bytes) {
ejsSetPropertyToString(ejs, thisObj, "status", "partialData");
httpCallback(hp, 500);
}
}
ISOURCE_Readable(source, hp->callback);
break;
}
}
/******************************************************************************/
/*
* Invoke the HTTP completion method
*/
static void httpCallback(HTTPControl *hp, int responseCode)
{
Ejs *ejs;
EjsVar *thisObj, *callbackObj;
MprArray *args;
char *msg;
const char *callbackMethod;
mprAssert(hp);
mprAssert(hp->webResp);
thisObj = hp->thisObj;
ejs = hp->ejs;
ejsSetPropertyToInteger(ejs, thisObj, "responseCode", responseCode);
if (mprGetBufLength(hp->buf) > 0) {
ejsSetPropertyToBinaryString(ejs, thisObj, "responseData",
mprGetBufStart(hp->buf), mprGetBufLength(hp->buf));
}
callbackObj = ejsGetPropertyAsVar(ejs, thisObj, "obj");
callbackMethod = ejsGetPropertyAsString(ejs, thisObj, "method");
if (callbackObj != 0 && callbackMethod != 0) {
args = mprCreateItemArray(ejs, EJS_INC_ARGS, EJS_MAX_ARGS);
mprAddItem(args, ejsDupVar(ejs, hp->thisObj, EJS_SHALLOW_COPY));
if (ejsRunMethod(ejs, callbackObj, callbackMethod, args) < 0) {
msg = ejsGetErrorMsg(ejs);
mprError(ejs, MPR_LOC, "HTTP callback failed. Details: %s", msg);
}
ejsFreeMethodArgs(ejs, args);
} else if (ejsRunMethod(ejs, thisObj, "onComplete", 0) < 0) {
msg = ejsGetErrorMsg(ejs);
mprError(ejs, MPR_LOC, "HTTP onComplete failed. Details: %s", msg);
}
cleanup(hp);
}
/******************************************************************************/
/*
* Cleanup
*/
static void cleanup(HTTPControl *hp)
{
Ejs *ejs;
MprApp *app;
int rc;
mprAssert(hp);
mprAssert(hp->webResp);
ejs = hp->ejs;
if (hp->webResp) {
rc = IWEBRESP_Release(hp->webResp);
// mprAssert(rc == 0);
hp->webResp = 0;
}
if (hp->callback) {
CALLBACK_Cancel(hp->callback);
mprFree(hp->callback);
hp->callback = 0;
}
/*
* Once the property is deleted, then if the destructor runs, it will
* notice that the EJS_HTTP_PROPERTY is undefined.
*/
ejsDeleteProperty(ejs, hp->thisObj, EJS_HTTP_PROPERTY);
/*
* Allow garbage collection to work on thisObj
*/
ejsMakeObjPermanent(hp->thisObj, 0);
ejsFreeVar(ejs, hp->thisObj);
mprFree(hp->buf);
mprFree(hp->url);
mprFree(hp);
app = mprGetApp(ejs);
ISHELL_SendEvent(app->shell, (AEECLSID) app->classId, EVT_USER, 0, 0);
}
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineHTTPClass(Ejs *ejs)
{
EjsVar *httpClass;
httpClass =
ejsDefineClass(ejs, "HTTP", "Object", ejsHTTPConstructor);
if (httpClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
/*
* Define the methods
*/
ejsDefineCMethod(ejs, httpClass, "fetch", fetchProc, 0);
ejsDefineCMethod(ejs, httpClass, "stop", stopProc, 0);
ejsDefineCMethod(ejs, httpClass, "setCallback", setCallback, 0);
#if FUTURE
ejsDefineCMethod(ejs, httpClass, "put", put, 0);
ejsDefineCMethod(ejs, httpClass, "upload", upload, 0);
ejsDefineCMethod(ejs, httpClass, "addUploadFile", addUploadFile, 0);
ejsDefineCMethod(ejs, httpClass, "addPostData", addPostData, 0);
ejsDefineCMethod(ejs, httpClass, "setUserPassword", setUserPassword, 0);
ejsDefineCMethod(ejs, httpClass, "addCookie", addCookie, 0);
#endif
/*
* Define properties
*/
ejsSetPropertyToString(ejs, httpClass, "status", "inactive");
/* This default should come from player.xml */
ejsSetPropertyToInteger(ejs, httpClass, "timeout", 30 * 1000);
ejsSetPropertyToInteger(ejs, httpClass, "responseCode", 0);
return ejsObjHasErrors(httpClass) ? MPR_ERR_CANT_INITIALIZE: 0;
}
/******************************************************************************/
void ejsTermHTTPClass(Ejs *ejs)
{
IWeb *web;
int rc;
web = (IWeb*) mprGetKeyValue(ejs, "bpWeb");
if (web) {
rc = IWEB_Release(web);
mprAssert(rc == 0);
}
}
#endif
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,326 @@
/*
* @file ejsGC.c
* @brief Garbage collector class for the EJS Object Model
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
/******************************************************************************/
/************************************ Methods *********************************/
/******************************************************************************/
#if (WIN || BREW_SIMULATOR) && BLD_DEBUG
static int checkProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
_CrtCheckMemory();
return 0;
}
#endif
/******************************************************************************/
static int debugProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 1) {
ejsError(ep, EJS_ARG_ERROR, "Bad args: debug(debugLevel)");
return -1;
}
ejsSetGCDebugLevel(ep, ejsVarToInteger(argv[0]));
return 0;
}
/******************************************************************************/
/*
* Print stats and dump objects
*/
static int printStatsProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
bool leakStats;
if (argc > 1) {
leakStats = ejsVarToInteger(argv[0]);
} else {
leakStats = 0;
}
#if BLD_FEATURE_ALLOC_STATS
ejsPrintAllocReport(ep, 0);
mprPrintAllocReport(mprGetApp(ep), leakStats, 0);
#endif
#if BLD_DEBUG
ejsDumpObjects(ep);
#endif
return 0;
}
/******************************************************************************/
static int runProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc > 1) {
ejsError(ep, EJS_ARG_ERROR, "Bad args: run([quick])");
return -1;
}
if (argc == 1) {
ejsIncrementalCollectGarbage(ep);
} else {
ejsCollectGarbage(ep, -1);
}
return 0;
}
/******************************************************************************/
static int usedMemoryProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValueToInteger(ep, ejsGetUsedMemory(ep));
return 0;
}
/******************************************************************************/
static int allocatedMemoryProc(Ejs *ep, EjsVar *thisObj, int argc,
EjsVar **argv)
{
#if BLD_FEATURE_ALLOC_STATS
ejsSetReturnValueToInteger(ep, ejsGetAllocatedMemory(ep));
#endif
return 0;
}
/******************************************************************************/
static int mprMemoryProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
#if BLD_FEATURE_ALLOC_STATS
ejsSetReturnValueToInteger(ep, mprGetAllocatedMemory(ep));
#endif
return 0;
}
/******************************************************************************/
static int peakMprMemoryProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
#if BLD_FEATURE_ALLOC_STATS
ejsSetReturnValueToInteger(ep, mprGetPeakAllocatedMemory(ep));
#endif
return 0;
}
/******************************************************************************/
static int getDebugLevel(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValueToInteger(ep, ep->gc.debugLevel);
return 0;
}
/******************************************************************************/
static int setDebugLevel(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 1) {
ejsArgError(ep, "Bad arguments");
return -1;
}
ep->gc.debugLevel= ejsVarToInteger(argv[0]);
return 0;
}
/******************************************************************************/
static int getEnable(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValueToBoolean(ep, ep->gc.enable);
return 0;
}
/******************************************************************************/
static int setEnable(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 1) {
ejsArgError(ep, "Bad arguments");
return -1;
}
ep->gc.enable= ejsVarToBoolean(argv[0]);
return 0;
}
/******************************************************************************/
static int getDemandCollect(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValueToBoolean(ep, ep->gc.enableDemandCollect);
return 0;
}
/******************************************************************************/
static int setDemandCollect(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 1) {
ejsArgError(ep, "Bad arguments");
return -1;
}
ep->gc.enableDemandCollect = ejsVarToBoolean(argv[0]);
return 0;
}
/******************************************************************************/
static int getIdleCollect(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValueToBoolean(ep, ep->gc.enableIdleCollect);
return 0;
}
/******************************************************************************/
static int setIdleCollect(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 1) {
ejsArgError(ep, "Bad arguments");
return -1;
}
ep->gc.enableIdleCollect = ejsVarToBoolean(argv[0]);
return 0;
}
/******************************************************************************/
static int getWorkQuota(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValueToInteger(ep, ep->gc.workQuota);
return 0;
}
/******************************************************************************/
static int setWorkQuota(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
int quota;
if (argc != 1) {
ejsArgError(ep, "Bad arguments");
return -1;
}
quota = ejsVarToInteger(argv[0]);
if (quota < EJS_GC_MIN_WORK_QUOTA && quota != 0) {
ejsArgError(ep, "Bad work quota");
return -1;
}
ep->gc.workQuota = quota;
return 0;
}
/******************************************************************************/
static int getMaxMemory(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValueToInteger(ep, ep->gc.maxMemory);
return 0;
}
/******************************************************************************/
static int setMaxMemory(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
int maxMemory;
if (argc != 1) {
ejsArgError(ep, "Bad arguments");
return -1;
}
maxMemory = ejsVarToInteger(argv[0]);
if (maxMemory < 0) {
ejsArgError(ep, "Bad maxMemory");
return -1;
}
ep->gc.maxMemory = maxMemory;
return 0;
}
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineGCClass(Ejs *ep)
{
EjsVar *gcClass;
int flags;
flags = EJS_NO_LOCAL;
/*
* NOTE: We create the GC class and define static methods on it. There
* is no object instance
*/
gcClass = ejsDefineClass(ep, "System.GC", "Object", 0);
if (gcClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
/*
* MOB -- convert these to properties with accessors when available
*/
ejsDefineCMethod(ep, gcClass, "printStats", printStatsProc, flags);
ejsDefineCMethod(ep, gcClass, "run", runProc, flags);
ejsDefineCMethod(ep, gcClass, "getUsedMemory", usedMemoryProc, flags);
ejsDefineCMethod(ep, gcClass, "getAllocatedMemory", allocatedMemoryProc,
flags);
ejsDefineCMethod(ep, gcClass, "getMprMemory", mprMemoryProc, flags);
ejsDefineCMethod(ep, gcClass, "getPeakMprMemory", peakMprMemoryProc, flags);
ejsDefineCMethod(ep, gcClass, "debug", debugProc, flags);
#if (WIN || BREW_SIMULATOR) && BLD_DEBUG
ejsDefineCMethod(ep, gcClass, "check", checkProc, flags);
#endif
ejsDefineCAccessors(ep, gcClass, "debugLevel",
getDebugLevel, setDebugLevel, flags);
ejsDefineCAccessors(ep, gcClass, "enable",
getEnable, setEnable, flags);
ejsDefineCAccessors(ep, gcClass, "demandCollect",
getDemandCollect, setDemandCollect, flags);
ejsDefineCAccessors(ep, gcClass, "idleCollect",
getIdleCollect, setIdleCollect, flags);
ejsDefineCAccessors(ep, gcClass, "workQuota",
getWorkQuota, setWorkQuota, flags);
ejsDefineCAccessors(ep, gcClass, "maxMemory",
getMaxMemory, setMaxMemory, flags);
return ejsObjHasErrors(gcClass) ? MPR_ERR_CANT_INITIALIZE : 0;
}
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
+785
View File
@@ -0,0 +1,785 @@
/*
* @file ejsGlobal.c
* @brief EJS support methods
*/
/********************************* Copyright **********************************/
/*
* @copy default
*
* Copyright (c) Mbedthis Software LLC, 2003-2006. All Rights Reserved.
* Copyright (c) Michael O'Brien, 1994-1995. All Rights Reserved.
*
* This software is distributed under commercial and open source licenses.
* You may use the GPL open source license described below or you may acquire
* a commercial license from Mbedthis Software. You agree to be fully bound
* by the terms of either license. Consult the LICENSE.TXT distributed with
* this software for full details.
*
* This software is open source; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See the GNU General Public License for more
* details at: http://www.mbedthis.com/downloads/gplLicense.html
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This GPL license does NOT permit incorporating this software into
* proprietary programs. If you are unable to comply with the GPL, you must
* acquire a commercial license to use this software. Commercial licenses
* for this software and support services are available from Mbedthis
* Software at http://www.mbedthis.com
*
* @end
*/
/********************************** Includes **********************************/
#include "ejs.h"
#if BLD_FEATURE_EJS
/******************************************************************************/
/************************************* Code ***********************************/
/******************************************************************************/
/*
* assert(condition)
*/
static int assertProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
int b;
if (argc < 1) {
ejsError(ep, EJS_ARG_ERROR, "usage: assert(condition)");
return -1;
}
b = ejsVarToBoolean(argv[0]);
if (b == 0) {
ejsError(ep, EJS_ASSERT_ERROR, "Assertion failure at line %d",
ejsGetLineNumber(ep));
return -1;
}
ejsWriteVarAsBoolean(ep, ep->result, b);
return 0;
}
/******************************************************************************/
/*
* breakpoint(msg)
*/
static int breakpointProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *buf;
if (argc < 1) {
return 0;
}
buf = ejsVarToString(ep, argv[0]);
if (buf) {
mprBreakpoint(0, buf);
}
return 0;
}
/******************************************************************************/
/*
* basename(path)
*/
static int basenameProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *path;
if (argc != 1) {
ejsError(ep, EJS_ARG_ERROR, "usage: basename(path)");
return -1;
}
path = ejsVarToString(ep, argv[0]);
if (path == 0) {
return MPR_ERR_MEMORY;
}
ejsSetReturnValueToString(ep, mprGetBaseName(path));
return 0;
}
/******************************************************************************/
/*
* stripext(path)
*/
static int stripextProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *cp, *path, *stripPath;
if (argc != 1) {
ejsError(ep, EJS_ARG_ERROR, "usage: stripext(path)");
return -1;
}
path = ejsVarToString(ep, argv[0]);
if (path == 0) {
return MPR_ERR_MEMORY;
}
stripPath = mprStrdup(ep, path);
if ((cp = strrchr(stripPath, '.')) != 0) {
*cp = '\0';
}
ejsSetReturnValueToString(ep, stripPath);
mprFree(stripPath);
return 0;
}
/******************************************************************************/
/*
* dirname(path)
*/
static int dirnameProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *path;
char dirname[MPR_MAX_FNAME];
if (argc != 1) {
ejsError(ep, EJS_ARG_ERROR, "usage: dirname(path)");
return -1;
}
path = ejsVarToString(ep, argv[0]);
if (path == 0) {
return MPR_ERR_MEMORY;
}
ejsSetReturnValueToString(ep,
mprGetDirName(dirname, sizeof(dirname), path));
return 0;
}
/******************************************************************************/
/*
* trim(string) -- trim white space
*/
static int trimProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *str, *buf, *cp;
if (argc != 1) {
ejsError(ep, EJS_ARG_ERROR, "usage: trim(string)");
return -1;
}
str = ejsVarToString(ep, argv[0]);
if (str == 0) {
return MPR_ERR_MEMORY;
}
str = buf = mprStrdup(ep, str);
while (isspace(*str)) {
str++;
}
cp = &str[strlen(str) - 1];
while (cp >= str) {
if (isspace(*cp)) {
*cp = '\0';
} else {
break;
}
cp--;
}
ejsSetReturnValueToString(ep, str);
mprFree(buf);
return 0;
}
/******************************************************************************/
/*
* Terminate the script
*/
static int exitScript(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
int status;
if (argc != 1) {
ejsError(ep, EJS_ARG_ERROR, "usage: exit(status)");
return -1;
}
status = (int) ejsVarToInteger(argv[0]);
ejsExit(ep, status);
ejsWriteVarAsString(ep, ep->result, "");
return 0;
}
/******************************************************************************/
/*
* include javascript libraries.
*/
static int includeProc(Ejs *ep, EjsVar *thisObj, int argc, char **argv)
{
int i;
mprAssert(argv);
for (i = 0; i < argc; i++) {
if (ejsEvalFile(ep, argv[i], 0) < 0) {
return -1;
}
}
return 0;
}
/******************************************************************************/
/*
* include javascript libraries at the global level
*/
static int includeGlobalProc(Ejs *ep, EjsVar *thisObj, int argc, char **argv)
{
int fid, i;
mprAssert(argv);
/*
* Create a new block and set the context to be the global scope
*/
fid = ejsSetBlock(ep, ep->global);
for (i = 0; i < argc; i++) {
if (ejsEvalFile(ep, argv[i], 0) < 0) {
ejsCloseBlock(ep, fid);
return -1;
}
}
ejsCloseBlock(ep, fid);
return 0;
}
/******************************************************************************/
#if BLD_DEBUG
/*
* Print variables to stdout
*/
static int printvProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
EjsVar *vp;
char *buf;
int i;
for (i = 0; i < argc; ) {
vp = argv[i++];
/* mprPrintf(ep, "arg[%d] = ", i); */
buf = ejsVarToString(ep, vp);
if (vp->propertyName == 0 || *vp->propertyName == '\0') {
mprPrintf(ep, "%s: ", buf);
} else if (i < argc) {
mprPrintf(ep, "%s = %s, ", vp->propertyName, buf);
} else {
mprPrintf(ep, "%s = %s\n", vp->propertyName, buf);
}
}
return 0;
}
#endif
/******************************************************************************/
/*
* Print the args to stdout
*/
static int printProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *buf;
int i;
for (i = 0; i < argc; i++) {
buf = ejsVarToString(ep, argv[i]);
mprPrintf(ep, "%s", buf);
}
return 0;
}
/******************************************************************************/
/*
* println
*/
static int printlnProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
printProc(ep, thisObj, argc, argv);
mprPrintf(ep, "\n");
return 0;
}
/******************************************************************************/
#if FUTURE
/*
* sprintf
*/
static int sprintfProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
va_list ap;
char *buf;
void **args;
int result;
if (argc <= 1) {
ejsError(ep, EJS_ARG_ERROR, "Usage: sprintf(fmt, [args ...])");
return -1;
}
args = mprAlloc(ep, sizeof(void*) * (argc - 1));
if (args == 0) {
mprAssert(args);
return -1;
}
for (i = 1; i < argc; i++) {
args[i - 1] = argv[i]);
}
va_start(ap, fmt);
*buf = 0;
result = inner(0, &buf, MPR_MAX_STRING, fmt, args);
va_end(ap);
ejsSetReturnValueToString(ep, buf);
mprFree(buf);
return 0;
}
/******************************************************************************/
inner(const char *fmt, void **args)
{
va_list ap;
va_start(ap, fmt);
*buf = 0;
mprSprintfCore(ctx, &buf, maxSize, fmt, ap, MPR_PRINTF_ARGV);
va_end(ap);
}
#endif
/******************************************************************************/
/*
* sleep
*/
static int sleepProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 1) {
ejsError(ep, EJS_ARG_ERROR, "Usage: sleep(milliseconds)");
return -1;
}
mprSleep(ep, ejsVarToInteger(argv[0]));
return 0;
}
/******************************************************************************/
/*
* sort properties
* FUTURE -- should have option to sort object based on a given property value
* ascending or descending
* Usage: sort(object, order = ascending, property = 0);
*/
static int sortProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
const char *property;
int error, order;
error = 0;
property = 0;
/*
* Default order is increasing
*/
order = 1;
if (argc < 1 || argc > 3 || !ejsVarIsObject(argv[0])) {
error++;
}
if (argc >= 2) {
order = ejsVarToInteger(argv[1]);
}
/*
* If property is not defined, it sorts the properties in the object
*/
if (argc == 3) {
if (! ejsVarIsString(argv[2])) {
error++;
} else {
property = argv[2]->string;
}
}
if (error) {
ejsError(ep, EJS_ARG_ERROR, "Usage: sort(object, [order], [property])");
return -1;
}
ejsSortProperties(ep, argv[0], 0, property, order);
return 0;
}
/******************************************************************************/
/*
* Get a time mark
* MOB -- WARNING: this can overflow. OK on BREW, but other O/Ss it may have
* overflowed on the first call. It should be renamed.
* MOB -- replace with proper Date.
*/
static int timeProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
MprTime now;
mprGetTime(ep, &now);
#if WIN || LINUX || SOLARIS
{
/* MOB -- poor hack */
static MprTime initial;
if (initial.sec == 0) {
initial = now;
}
now.sec -= initial.sec;
if (initial.msec > now.msec) {
now.msec = now.msec + 1000 - initial.msec;
now.sec--;
} else {
now.msec -= initial.msec;
}
}
#endif
/* MOB -- this can overflow */
ejsSetReturnValueToInteger(ep, now.sec * 1000 + now.msec);
return 0;
}
/******************************************************************************/
/*
* MOB -- Temporary Get the date (time since Jan 6, 1980 GMT
*/
static int dateProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
#if BREW
uint now;
now = GETTIMESECONDS();
ejsSetReturnValueToInteger(ep, now);
#endif
return 0;
}
/******************************************************************************/
/*
* strlen(string)
*/
static int strlenProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *buf;
int len;
if (argc != 1) {
ejsError(ep, EJS_ARG_ERROR, "Usage: strlen(var)");
return -1;
}
len = 0;
if (! ejsVarIsString(argv[0])) {
buf = ejsVarToString(ep, argv[0]);
if (buf) {
len = strlen(buf);
}
} else {
len = argv[0]->length;
}
ejsSetReturnValueToInteger(ep, len);
return 0;
}
/******************************************************************************/
/*
* toint(num)
*/
static int tointProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
int i;
if (argc != 1) {
ejsError(ep, EJS_ARG_ERROR, "Usage: toint(number)");
return -1;
}
i = ejsVarToInteger(argv[0]);
ejsSetReturnValueToInteger(ep, i);
return 0;
}
/******************************************************************************/
/*
* string strstr(string, pat)
*/
static int strstrProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
char *str, *pat;
char *s;
int strAlloc;
if (argc != 2) {
ejsError(ep, EJS_ARG_ERROR, "Usage: strstr(string, pat)");
return -1;
}
str = ejsVarToString(ep, argv[0]);
strAlloc = ep->castAlloc;
ep->castTemp = 0;
pat = ejsVarToString(ep, argv[1]);
s = strstr(str, pat);
if (s == 0) {
ejsSetReturnValueToUndefined(ep);
} else {
ejsSetReturnValueToString(ep, s);
}
if (strAlloc) {
mprFree(str);
}
return 0;
}
/******************************************************************************/
/*
* Trace
*/
static int traceProc(Ejs *ep, EjsVar *thisObj, int argc, char **argv)
{
if (argc == 1) {
mprLog(ep, 0, "%s", argv[0]);
} else if (argc == 2) {
mprLog(ep, atoi(argv[0]), "%s", argv[1]);
} else {
ejsError(ep, EJS_ARG_ERROR, "Usage: trace([level], message)");
return -1;
}
ejsWriteVarAsString(ep, ep->result, "");
return 0;
}
/******************************************************************************/
/*
* Evaluate a sub-script. It is evaluated in the same variable scope as
* the calling script / method.
*/
static int evalScriptProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
EjsVar *arg;
int i;
ejsWriteVarAsUndefined(ep, ep->result);
for (i = 0; i < argc; i++) {
arg = argv[i];
if (arg->type != EJS_TYPE_STRING) {
continue;
}
if (ejsEvalScript(ep, arg->string, 0) < 0) {
return -1;
}
}
/*
* Return with the value of the last expression
*/
return 0;
}
/******************************************************************************/
/* MOB -- need a real datatype returning int, int64, etc */
static int typeofProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
const struct {
EjsType type;
const char *name;
} types[] = {
{ EJS_TYPE_UNDEFINED, "undefined" },
#if EJS_ECMA_STND
{ EJS_TYPE_NULL, "object" },
#else
{ EJS_TYPE_NULL, "null" },
#endif
{ EJS_TYPE_BOOL, "boolean" },
{ EJS_TYPE_CMETHOD, "function" },
{ EJS_TYPE_FLOAT, "number" },
{ EJS_TYPE_INT, "number" },
{ EJS_TYPE_INT64, "number" },
{ EJS_TYPE_OBJECT, "object" },
{ EJS_TYPE_METHOD, "function" },
{ EJS_TYPE_STRING, "string" },
{ EJS_TYPE_STRING_CMETHOD, "function" },
{ EJS_TYPE_PTR, "pointer" }
};
const char *type;
int i;
type = NULL;
if (argc != 1) {
ejsError(ep, EJS_ARG_ERROR, "Bad args: typeof(var)");
return -1;
}
for (i = 0; i < MPR_ARRAY_SIZE(types); i++) {
if (argv[0]->type == types[i].type) {
type = types[i].name;
break;
}
}
if (type == NULL) {
mprAssert(type);
return -1;
}
ejsSetReturnValueToString(ep, type);
return 0;
}
/******************************************************************************/
/*
* Define the standard properties and methods inherited by all interpreters
* Obj is set to the global class in the default interpreter. When an
* interpreter attempts to write to any property, a copy will be written
* into the interpeters own global space. This is like a "copy-on-write".
*/
int ejsDefineGlobalProperties(Ejs *ep)
{
EjsVar *obj;
obj = ep->service->globalClass;
mprAssert(obj);
ejsSetPropertyToNull(ep, obj, "null");
ejsSetPropertyToUndefined(ep, obj, "undefined");
ejsSetPropertyToBoolean(ep, obj, "true", 1);
ejsSetPropertyToBoolean(ep, obj, "false", 0);
#if BLD_FEATURE_FLOATING_POINT
{
/* MOB. Fix. This generates warnings on some systems.
This is intended. */
double d = 0.0;
double e = 0.0;
ejsSetPropertyToFloat(ep, obj, "NaN", e / d);
d = MAX_FLOAT;
ejsSetPropertyToFloat(ep, obj, "Infinity", d * d);
}
#endif
#if BLD_FEATURE_LEGACY_API
/*
* DEPRECATED: 2.0.
* So that ESP/ASP can ignore "language=javascript" statements
*/
ejsSetPropertyToInteger(ep, obj, "javascript", 0);
#endif
/*
* Extension methods. We go directly to the mpr property APIs for speed.
* Flags will cause the callbacks to be supplied the Ejs handle.
*/
ejsDefineCMethod(ep, obj, "assert", assertProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "breakpoint", breakpointProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "basename", basenameProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "dirname", dirnameProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "stripext", stripextProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "trim", trimProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "eval", evalScriptProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "exit", exitScript, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "print", printProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "println", printlnProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "sleep", sleepProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "sort", sortProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "time", timeProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "date", dateProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "strlen", strlenProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "strstr", strstrProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "typeof", typeofProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "toint", tointProc, EJS_NO_LOCAL);
ejsDefineStringCMethod(ep, obj, "include", includeProc, EJS_NO_LOCAL);
ejsDefineStringCMethod(ep, obj, "includeGlobal", includeGlobalProc,
EJS_NO_LOCAL);
ejsDefineStringCMethod(ep, obj, "trace", traceProc, EJS_NO_LOCAL);
#if BLD_DEBUG
ejsDefineCMethod(ep, obj, "printv", printvProc, EJS_NO_LOCAL);
#endif
#if FUTURE
ejsDefineCMethod(ep, obj, "printf", printfProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, obj, "sprintf", sprintfProc, EJS_NO_LOCAL);
#endif
if (ejsObjHasErrors(obj)) {
return MPR_ERR_CANT_INITIALIZE;
}
return 0;
}
/******************************************************************************/
#else
void ejsProcsDummy() {}
/******************************************************************************/
#endif /* BLD_FEATURE_EJS */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,112 @@
/*
* @file ejsSystem.c
* @brief System class for the EJS Object Model
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
/******************************************************************************/
/************************************ Methods *********************************/
/******************************************************************************/
#if UNUSED
/*
* function int random()
*/
static int randomProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "random()\n");
return 0;
}
/******************************************************************************/
/*
* function void yield()
*/
static int yieldProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "yield()\n");
return 0;
}
/******************************************************************************/
/*
* function void sleep(int milliSeconds)
*/
static int sleepProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ep, "sleep()\n");
return 0;
}
#endif
/******************************************************************************/
/*
* function void exit(int status)
*
* Exit the widget with the given status. All JavaScript processing ceases.
*/
static int exitProc(Ejs *ep, EjsVar *thisObj, int argc, EjsVar **argv)
{
int status;
status = 0;
if ((argc == 1) && ejsVarIsInteger(argv[0])) {
status = argv[0]->integer;
}
ejsExit(ep, status);
return 0;
}
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineSystemClass(Ejs *ep)
{
EjsVar *systemClass;
/*
* We create the system class and define static methods on it.
* NOTE: There is no object instance
*/
systemClass = ejsDefineClass(ep, "System", "Object", 0);
if (systemClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
ejsDefineCMethod(ep, systemClass, "exit", exitProc, EJS_NO_LOCAL);
#if UNUSED
ejsDefineCMethod(ep, systemClass, "random", randomProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, systemClass, "yield", yieldProc, EJS_NO_LOCAL);
ejsDefineCMethod(ep, systemClass, "sleep", sleepProc, EJS_NO_LOCAL);
/*
* Define properties
*/
ejsSetPropertyToString(systemClass, "name", "");
#endif
return ejsObjHasErrors(systemClass) ? MPR_ERR_CANT_INITIALIZE : 0;
}
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,49 @@
/*
* @file ejsSystemApp.c
* @brief App class
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software Inc, 2005-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
/************************************ Code ************************************/
int ejsDefineAppClass(Ejs *ep)
{
EjsVar *appClass;
appClass = ejsDefineClass(ep, "System.App", "Object", 0);
if (appClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
/*
* Define properties
*/
ejsSetPropertyToString(ep, appClass, "name", BLD_PRODUCT);
ejsSetPropertyToString(ep, appClass, "title", BLD_NAME);
ejsSetPropertyToString(ep, appClass, "version", BLD_VERSION);
/*
* Command line arguments
*/
ejsSetPropertyToNull(ep, appClass, "args");
return ejsObjHasErrors(appClass) ? MPR_ERR_CANT_INITIALIZE : 0;
}
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,60 @@
/*
* @file ejsSystemDebug.c
* @brief System.Debug class
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
/******************************************************************************/
/************************************ Methods *********************************/
/******************************************************************************/
/*
* function bool isDebugMode()
* MOB -- convert to accessor
*/
static int isDebugMode(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsTrace(ejs, "isDebugMode()\n");
ejsSetReturnValueToInteger(ejs, mprGetDebugMode(ejs));
return 0;
}
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineDebugClass(Ejs *ejs)
{
EjsVar *systemDebugClass;
systemDebugClass = ejsDefineClass(ejs, "System.Debug", "Object", 0);
if (systemDebugClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
/*
* Define the class methods
*/
ejsDefineCMethod(ejs, systemDebugClass, "isDebugMode", isDebugMode,
EJS_NO_LOCAL);
return ejsObjHasErrors(systemDebugClass) ? MPR_ERR_CANT_INITIALIZE : 0;
}
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,163 @@
/*
* @file ejsSystemLog.c
* @brief System.Log class for the EJS Object Model
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
/*********************************** Usage ************************************/
/*
* System.Log.setLog(path);
* System.Log.enable;
*/
/******************************************************************************/
static void logHandler(MPR_LOC_DEC(ctx, loc), int flags, int level,
const char *msg)
{
MprApp *app;
char *buf;
int len;
app = mprGetApp(ctx);
if (app->logFile == 0) {
return;
}
if (flags & MPR_LOG_SRC) {
len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0,
"Log %d: %s\n", level, msg);
} else if (flags & MPR_ERROR_SRC) {
len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0,
"Error: %s\n", msg);
} else if (flags & MPR_FATAL_SRC) {
len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0,
"Fatal: %s\n", msg);
} else if (flags & MPR_ASSERT_SRC) {
#if BLD_FEATURE_ALLOC_LEAK_TRACK
len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0,
"Assertion %s, failed at %s\n",
msg, loc);
#else
len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0,
"Assertion %s, failed\n", msg);
#endif
} else if (flags & MPR_RAW) {
/* OPT */
len = mprAllocSprintf(MPR_LOC_PASS(ctx, loc), &buf, 0,
"%s", msg);
} else {
return;
}
mprPuts(app->logFile, buf, len);
mprFree(buf);
}
/******************************************************************************/
/************************************ Methods *********************************/
/******************************************************************************/
/*
* function int setLog(string path)
*/
static int setLog(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
const char *path;
MprFile *file;
MprApp *app;
if (argc != 1 || !ejsVarIsString(argv[0])) {
ejsArgError(ejs, "Usage: setLog(path)");
return -1;
}
app = mprGetApp(ejs);
/*
* Ignore errors if we can't create the log file.
* Use the app context so this will live longer than the interpreter
* MOB -- this leaks files.
*/
path = argv[0]->string;
file = mprOpen(app, path, O_CREAT | O_TRUNC | O_WRONLY, 0664);
if (file) {
app->logFile = file;
mprSetLogHandler(ejs, logHandler);
}
mprLog(ejs, 0, "Test log");
return 0;
}
/******************************************************************************/
#if UNUSED
static int enableSetAccessor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
if (argc != 1) {
ejsArgError(ejs, "Usage: set(value)");
return -1;
}
ejsSetProperty(ejs, thisObj, "_enabled", argv[0]);
return 0;
}
/******************************************************************************/
static int enableGetAccessor(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValue(ejs, ejsGetPropertyAsVar(ejs, thisObj, "_enabled"));
return 0;
}
#endif
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineLogClass(Ejs *ejs)
{
EjsVar *logClass;
logClass = ejsDefineClass(ejs, "System.Log", "Object", 0);
if (logClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
ejsDefineCMethod(ejs, logClass, "setLog", setLog, EJS_NO_LOCAL);
#if UNUSED
EjsProperty *pp;
ejsDefineCAccessors(ejs, logClass, "enable", enableSetAccessor,
enableGetAccessor, EJS_NO_LOCAL);
pp = ejsSetPropertyToBoolean(ejs, logClass, "_enabled", 0);
ejsMakePropertyEnumerable(pp, 0);
#endif
return ejsObjHasErrors(logClass) ? MPR_ERR_CANT_INITIALIZE : 0;
}
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
@@ -0,0 +1,174 @@
/*
* @file ejsSystemMemory.c
* @brief System.Memory class
*/
/********************************** Copyright *********************************/
/*
* Copyright (c) Mbedthis Software LLC, 2005-2006. All Rights Reserved.
*/
/********************************** Includes **********************************/
#include "ejs.h"
/****************************** Forward Declarations***************************/
static uint getUsedMemory(Ejs *ejs);
/******************************************************************************/
/*********************************** Methods *********************************/
/******************************************************************************/
static int getUsedMemoryProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValueToInteger(ejs, getUsedMemory(ejs));
return 0;
}
/******************************************************************************/
static int getUsedStackProc(Ejs *ejs, EjsVar *thisObj, int argc, EjsVar **argv)
{
ejsSetReturnValueToInteger(ejs, mprStackSize(ejs));
return 0;
}
/******************************************************************************/
/*
* Public function
*/
uint ejsGetAvailableMemory(Ejs *ejs)
{
EjsVar *memoryClass;
uint ram;
memoryClass = ejsGetClass(ejs, 0, "System.Memory");
ram = ejsGetPropertyAsInteger(ejs, memoryClass, "ram");
return ram - getUsedMemory(ejs);
}
/******************************************************************************/
static int getAvailableMemoryProc(Ejs *ejs, EjsVar *thisObj, int argc,
EjsVar **argv)
{
EjsVar *memoryClass;
uint ram;
memoryClass = ejsGetClass(ejs, 0, "System.Memory");
ram = ejsGetPropertyAsInteger(ejs, memoryClass, "ram");
#if BREW
ejsSetReturnValueToInteger(ejs, ram - getUsedMemory(ejs));
#else
ejsSetReturnValueToInteger(ejs, 0);
#endif
return 0;
}
/******************************************************************************/
static uint getUsedMemory(Ejs *ejs)
{
#if BREW
MprApp *app;
IHeap *heap;
uint memInUse;
void *ptr;
app = mprGetApp(ejs);
ptr = (void*) &heap;
if (ISHELL_CreateInstance(app->shell, AEECLSID_HEAP, (void**) ptr)
== SUCCESS) {
memInUse = IHEAP_GetMemStats(heap);
IHEAP_Release(heap);
} else {
memInUse = 0;
}
return memInUse;
#else
return 0;
#endif
}
/******************************************************************************/
/******************************** Initialization ******************************/
/******************************************************************************/
int ejsDefineMemoryClass(Ejs *ejs)
{
EjsVar *memoryClass;
uint used;
#if BREW
MprApp *app;
AEEDeviceInfo *info;
/*
* Get needed information for class properties.
*/
info = mprAllocType(ejs, AEEDeviceInfo);
if (info == 0) {
return MPR_ERR_CANT_ALLOCATE;
}
info->wStructSize = sizeof(AEEDeviceInfo);
app = mprGetApp(ejs);
ISHELL_GetDeviceInfo(app->shell, info);
used = getUsedMemory(ejs);
#else
used = 0;
#endif
/*
* Create the class
*/
memoryClass = ejsDefineClass(ejs, "System.Memory", "Object", 0);
if (memoryClass == 0) {
return MPR_ERR_CANT_INITIALIZE;
}
/*
* Define the class methods
* MOB -- change to accessors
*/
ejsDefineCMethod(ejs, memoryClass, "getUsedStack", getUsedStackProc,
EJS_NO_LOCAL);
ejsDefineCMethod(ejs, memoryClass, "getUsedMemory", getUsedMemoryProc,
EJS_NO_LOCAL);
ejsDefineCMethod(ejs, memoryClass, "getAvailableMemory",
getAvailableMemoryProc, EJS_NO_LOCAL);
/*
* Define properties
*/
#if BREW
ejsSetPropertyToInteger(ejs, memoryClass, "ram", info->dwRAM);
#if UNUSED
/* MOB -- delete this */
ejsSetPropertyToInteger(ejs, memoryClass, "available",
info->dwRAM - used);
#endif
#endif
#if UNUSED
ejsSetPropertyToInteger(ejs, memoryClass, "used", used);
ejsSetPropertyToInteger(ejs, memoryClass, "flash", 0);
#endif
return ejsObjHasErrors(memoryClass) ? MPR_ERR_CANT_INITIALIZE : 0;
}
/******************************************************************************/
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim:tw=78
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/