#include <stdio.h>
#include <string.h>
#include "value.h"
#include "object.h"
#include "types.h"
#include "interpreter.h"
using namespace KJS;
class TestFunctionImp : public ObjectImp {
public:
TestFunctionImp() : ObjectImp() {}
virtual bool implementsCall() const { return true; }
virtual Value call(ExecState *exec, Object &thisObj, const List &args);
};
Value TestFunctionImp::call(ExecState *exec, Object &, const List &args)
{
fprintf(stderr,"--> %s\n",args[0].toString(exec).ascii());
return Undefined();
}
class VersionFunctionImp : public ObjectImp {
public:
VersionFunctionImp() : ObjectImp() {}
virtual bool implementsCall() const { return true; }
virtual Value call(ExecState *exec, Object &thisObj, const List &args);
};
Value VersionFunctionImp::call(ExecState *exec, Object &, const List &args)
{
return Undefined();
}
class GlobalImp : public ObjectImp {
public:
virtual UString className() const { return "global"; }
};
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "You have to specify at least one filename\n");
return -1;
}
bool ret = true;
{
Interpreter::lock();
Object global(new GlobalImp());
Interpreter interp(global);
global.put(interp.globalExec(), Identifier("debug"), Object(new TestFunctionImp()));
global.put(interp.globalExec(), Identifier("print"), Object(new TestFunctionImp()));
global.put(interp.globalExec(), Identifier("version"), Object(new VersionFunctionImp()));
const int BufferSize = 200000;
char code[BufferSize];
for (int i = 1; i < argc; i++) {
const char *file = argv[i];
if (strcmp(file, "-f") == 0)
continue;
FILE *f = fopen(file, "r");
if (!f) {
fprintf(stderr, "Error opening %s.\n", file);
return 2;
}
int num = fread(code, 1, BufferSize, f);
code[num] = '\0';
if(num >= BufferSize)
fprintf(stderr, "Warning: File may have been too long.\n");
Completion comp(interp.evaluate(file, 1, code));
fclose(f);
if (comp.complType() == Throw) {
ExecState *exec = interp.globalExec();
Value exVal = comp.value();
char *msg = exVal.toString(exec).ascii();
int lineno = -1;
if (exVal.type() == ObjectType) {
Value lineVal = Object::dynamicCast(exVal).get(exec,Identifier("line"));
if (lineVal.type() == NumberType)
lineno = int(lineVal.toNumber(exec));
}
if (lineno != -1)
fprintf(stderr,"Exception, line %d: %s\n",lineno,msg);
else
fprintf(stderr,"Exception: %s\n",msg);
ret = false;
}
else if (comp.complType() == ReturnValue) {
char *msg = comp.value().toString(interp.globalExec()).ascii();
fprintf(stderr,"Return value: %s\n",msg);
}
}
Interpreter::unlock();
}
if (ret)
fprintf(stderr, "OK.\n");
#ifdef KJS_DEBUG_MEM
Interpreter::finalCheck();
#endif
return ret ? 0 : 3;
}