squirrel.cpp

Go to the documentation of this file.
00001 /* $Id: squirrel.cpp 15531 2009-02-20 13:39:18Z yexo $ */
00002 
00005 #include <squirrel.h>
00006 #include <stdarg.h>
00007 #include "../stdafx.h"
00008 #include "../debug.h"
00009 #include "squirrel.hpp"
00010 #include "squirrel_std.hpp"
00011 #include "../fileio_func.h"
00012 #include <sqstdaux.h>
00013 #include <../squirrel/sqpcheader.h>
00014 #include <../squirrel/sqvm.h>
00015 
00016 void Squirrel::CompileError(HSQUIRRELVM vm, const SQChar *desc, const SQChar *source, SQInteger line, SQInteger column)
00017 {
00018   SQChar buf[1024];
00019 
00020 #ifdef _SQ64
00021   scsnprintf(buf, lengthof(buf), _SC("Error %s:%ld/%ld: %s"), source, line, column, desc);
00022 #else
00023   scsnprintf(buf, lengthof(buf), _SC("Error %s:%d/%d: %s"), source, line, column, desc);
00024 #endif
00025 
00026   /* Check if we have a custom print function */
00027   Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
00028   engine->crashed = true;
00029   SQPrintFunc *func = engine->print_func;
00030   if (func == NULL) {
00031     scfprintf(stderr, _SC("%s"), buf);
00032   } else {
00033     (*func)(true, buf);
00034   }
00035 }
00036 
00037 void Squirrel::ErrorPrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
00038 {
00039   va_list arglist;
00040   SQChar buf[1024];
00041 
00042   va_start(arglist, s);
00043   scvsnprintf(buf, lengthof(buf), s, arglist);
00044   va_end(arglist);
00045 
00046   /* Check if we have a custom print function */
00047   SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
00048   if (func == NULL) {
00049     scfprintf(stderr, _SC("%s"), buf);
00050   } else {
00051     (*func)(true, buf);
00052   }
00053 }
00054 
00055 void Squirrel::RunError(HSQUIRRELVM vm, const SQChar *error)
00056 {
00057   /* Set the print function to something that prints to stderr */
00058   SQPRINTFUNCTION pf = sq_getprintfunc(vm);
00059   sq_setprintfunc(vm, &Squirrel::ErrorPrintFunc);
00060 
00061   /* Check if we have a custom print function */
00062   SQChar buf[1024];
00063   scsnprintf(buf, lengthof(buf), _SC("Your script made an error: %s\n"), error);
00064   Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
00065   SQPrintFunc *func = engine->print_func;
00066   if (func == NULL) {
00067     scfprintf(stderr, _SC("%s"), buf);
00068   } else {
00069     (*func)(true, buf);
00070   }
00071 
00072   /* Print below the error the stack, so the users knows what is happening */
00073   sqstd_printcallstack(vm);
00074   /* Reset the old print function */
00075   sq_setprintfunc(vm, pf);
00076 }
00077 
00078 SQInteger Squirrel::_RunError(HSQUIRRELVM vm)
00079 {
00080   const SQChar *sErr = 0;
00081 
00082   if (sq_gettop(vm) >= 1) {
00083     if (SQ_SUCCEEDED(sq_getstring(vm, -1, &sErr))) {
00084       Squirrel::RunError(vm, sErr);
00085       return 0;
00086     }
00087   }
00088 
00089   Squirrel::RunError(vm, _SC("unknown error"));
00090   return 0;
00091 }
00092 
00093 void Squirrel::PrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
00094 {
00095   va_list arglist;
00096   SQChar buf[1024];
00097 
00098   va_start(arglist, s);
00099   scvsnprintf(buf, lengthof(buf) - 2, s, arglist);
00100   va_end(arglist);
00101   scstrcat(buf, _SC("\n"));
00102 
00103   /* Check if we have a custom print function */
00104   SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
00105   if (func == NULL) {
00106     scprintf(_SC("%s"), buf);
00107   } else {
00108     (*func)(false, buf);
00109   }
00110 }
00111 
00112 void Squirrel::AddMethod(const char *method_name, SQFUNCTION proc, uint nparam, const char *params, void *userdata, int size)
00113 {
00114   sq_pushstring(this->vm, OTTD2FS(method_name), -1);
00115 
00116   if (size != 0) {
00117     void *ptr = sq_newuserdata(vm, size);
00118     memcpy(ptr, userdata, size);
00119   }
00120 
00121   sq_newclosure(this->vm, proc, size != 0 ? 1 : 0);
00122   if (nparam != 0) sq_setparamscheck(this->vm, nparam, OTTD2FS(params));
00123   sq_setnativeclosurename(this->vm, -1, OTTD2FS(method_name));
00124   sq_newslot(this->vm, -3, SQFalse);
00125 }
00126 
00127 void Squirrel::AddConst(const char *var_name, int value)
00128 {
00129   sq_pushstring(this->vm, OTTD2FS(var_name), -1);
00130   sq_pushinteger(this->vm, value);
00131   sq_newslot(this->vm, -3, SQTrue);
00132 }
00133 
00134 void Squirrel::AddClassBegin(const char *class_name)
00135 {
00136   sq_pushroottable(this->vm);
00137   sq_pushstring(this->vm, OTTD2FS(class_name), -1);
00138   sq_newclass(this->vm, SQFalse);
00139 }
00140 
00141 void Squirrel::AddClassBegin(const char *class_name, const char *parent_class)
00142 {
00143   sq_pushroottable(this->vm);
00144   sq_pushstring(this->vm, OTTD2FS(class_name), -1);
00145   sq_pushstring(this->vm, OTTD2FS(parent_class), -1);
00146   if (SQ_FAILED(sq_get(this->vm, -3))) {
00147     DEBUG(misc, 0, "[squirrel] Failed to initialize class '%s' based on parent class '%s'", class_name, parent_class);
00148     DEBUG(misc, 0, "[squirrel] Make sure that '%s' exists before trying to define '%s'", parent_class, class_name);
00149     return;
00150   }
00151   sq_newclass(this->vm, SQTrue);
00152 }
00153 
00154 void Squirrel::AddClassEnd()
00155 {
00156   sq_newslot(vm, -3, SQFalse);
00157   sq_pop(vm, 1);
00158 }
00159 
00160 bool Squirrel::MethodExists(HSQOBJECT instance, const char *method_name)
00161 {
00162   assert(!this->crashed);
00163   int top = sq_gettop(this->vm);
00164   /* Go to the instance-root */
00165   sq_pushobject(this->vm, instance);
00166   /* Find the function-name inside the script */
00167   sq_pushstring(this->vm, OTTD2FS(method_name), -1);
00168   if (SQ_FAILED(sq_get(this->vm, -2))) {
00169     sq_settop(this->vm, top);
00170     return false;
00171   }
00172   sq_settop(this->vm, top);
00173   return true;
00174 }
00175 
00176 bool Squirrel::Resume(int suspend)
00177 {
00178   assert(!this->crashed);
00179   this->crashed = !sq_resumecatch(this->vm, suspend);
00180   return this->vm->_suspended != 0;
00181 }
00182 
00183 void Squirrel::CollectGarbage()
00184 {
00185   sq_collectgarbage(this->vm);
00186 }
00187 
00188 bool Squirrel::CallMethod(HSQOBJECT instance, const char *method_name, HSQOBJECT *ret, int suspend)
00189 {
00190   assert(!this->crashed);
00191   /* Store the stack-location for the return value. We need to
00192    * restore this after saving or the stack will be corrupted
00193    * if we're in the middle of a DoCommand. */
00194   SQInteger last_target = this->vm->_suspended_target;
00195   /* Store the current top */
00196   int top = sq_gettop(this->vm);
00197   /* Go to the instance-root */
00198   sq_pushobject(this->vm, instance);
00199   /* Find the function-name inside the script */
00200   sq_pushstring(this->vm, OTTD2FS(method_name), -1);
00201   if (SQ_FAILED(sq_get(this->vm, -2))) {
00202     DEBUG(misc, 0, "[squirrel] Could not find '%s' in the class", method_name);
00203     sq_settop(this->vm, top);
00204     return false;
00205   }
00206   /* Call the method */
00207   sq_pushobject(this->vm, instance);
00208   if (SQ_FAILED(sq_call(this->vm, 1, ret == NULL ? SQFalse : SQTrue, SQTrue, suspend))) return false;
00209   if (ret != NULL) sq_getstackobj(vm, -1, ret);
00210   /* Reset the top, but don't do so for the AI main function, as we need
00211    *  a correct stack when resuming. */
00212   if (suspend == -1) sq_settop(this->vm, top);
00213   /* Restore the return-value location. */
00214   this->vm->_suspended_target = last_target;
00215 
00216   return true;
00217 }
00218 
00219 bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance, const char *method_name, const char **res, int suspend)
00220 {
00221   HSQOBJECT ret;
00222   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
00223   if (ret._type != OT_STRING) return false;
00224   *res = strdup(ObjectToString(&ret));
00225   return true;
00226 }
00227 
00228 bool Squirrel::CallIntegerMethod(HSQOBJECT instance, const char *method_name, int *res, int suspend)
00229 {
00230   HSQOBJECT ret;
00231   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
00232   if (ret._type != OT_INTEGER) return false;
00233   *res = ObjectToInteger(&ret);
00234   return true;
00235 }
00236 
00237 /* static */ bool Squirrel::CreateClassInstanceVM(HSQUIRRELVM vm, const char *class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook)
00238 {
00239   int oldtop = sq_gettop(vm);
00240 
00241   /* First, find the class */
00242   sq_pushroottable(vm);
00243   sq_pushstring(vm, OTTD2FS(class_name), -1);
00244   if (SQ_FAILED(sq_get(vm, -2))) {
00245     DEBUG(misc, 0, "[squirrel] Failed to find class by the name '%s'", class_name);
00246     sq_settop(vm, oldtop);
00247     return false;
00248   }
00249 
00250   /* Create the instance */
00251   if (SQ_FAILED(sq_createinstance(vm, -1))) {
00252     DEBUG(misc, 0, "[squirrel] Failed to create instance for class '%s'", class_name);
00253     sq_settop(vm, oldtop);
00254     return false;
00255   }
00256 
00257   if (instance != NULL) {
00258     /* Find our instance */
00259     sq_getstackobj(vm, -1, instance);
00260     /* Add a reference to it, so it survives for ever */
00261     sq_addref(vm, instance);
00262   }
00263   sq_remove(vm, -2); // Class-name
00264   sq_remove(vm, -2); // Root-table
00265 
00266   /* Store it in the class */
00267   sq_setinstanceup(vm, -1, real_instance);
00268   if (release_hook != NULL) sq_setreleasehook(vm, -1, release_hook);
00269 
00270   if (instance != NULL) sq_settop(vm, oldtop);
00271 
00272   return true;
00273 }
00274 
00275 bool Squirrel::CreateClassInstance(const char *class_name, void *real_instance, HSQOBJECT *instance)
00276 {
00277   return Squirrel::CreateClassInstanceVM(this->vm, class_name, real_instance, instance, NULL);
00278 }
00279 
00280 Squirrel::Squirrel()
00281 {
00282   this->vm = sq_open(1024);
00283   this->print_func = NULL;
00284   this->global_pointer = NULL;
00285   this->crashed = false;
00286 
00287   /* Handle compile-errors ourself, so we can display it nicely */
00288   sq_setcompilererrorhandler(this->vm, &Squirrel::CompileError);
00289   sq_notifyallexceptions(this->vm, SQTrue);
00290   /* Set a good print-function */
00291   sq_setprintfunc(this->vm, &Squirrel::PrintFunc);
00292   /* Handle runtime-errors ourself, so we can display it nicely */
00293   sq_newclosure(this->vm, &Squirrel::_RunError, 0);
00294   sq_seterrorhandler(this->vm);
00295 
00296   /* Set the foreigh pointer, so we can always find this instance from within the VM */
00297   sq_setforeignptr(this->vm, this);
00298 
00299   sq_pushroottable(this->vm);
00300   squirrel_register_global_std(this);
00301 }
00302 
00303 class SQFile {
00304 private:
00305   FILE *file;
00306   size_t size;
00307   size_t pos;
00308 
00309 public:
00310   SQFile(FILE *file, size_t size) : file(file), size(size), pos(0) {}
00311 
00312   size_t Read(void *buf, size_t elemsize, size_t count)
00313   {
00314     assert(elemsize != 0);
00315     if (this->pos + (elemsize * count) > this->size) {
00316       count = (this->size - this->pos) / elemsize;
00317     }
00318     if (count == 0) return 0;
00319     size_t ret = fread(buf, elemsize, count, this->file);
00320     this->pos += ret * elemsize;
00321     return ret;
00322   }
00323 };
00324 
00325 static SQInteger _io_file_lexfeed_ASCII(SQUserPointer file)
00326 {
00327   char c;
00328   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return c;
00329   return 0;
00330 }
00331 
00332 static SQInteger _io_file_lexfeed_UTF8(SQUserPointer file)
00333 {
00334   static const SQInteger utf8_lengths[16] =
00335   {
00336     1, 1, 1, 1, 1, 1, 1, 1, /* 0000 to 0111 : 1 byte (plain ASCII) */
00337     0, 0, 0, 0,             /* 1000 to 1011 : not valid */
00338     2, 2,                   /* 1100, 1101 : 2 bytes */
00339     3,                      /* 1110 : 3 bytes */
00340     4                       /* 1111 : 4 bytes */
00341   };
00342   static unsigned char byte_masks[5] = {0, 0, 0x1F, 0x0F, 0x07};
00343   unsigned char inchar;
00344   SQInteger c = 0;
00345   if (((SQFile *)file)->Read(&inchar, sizeof(inchar), 1) != 1) return 0;
00346   c = inchar;
00347 
00348   if (c >= 0x80) {
00349     SQInteger tmp;
00350     SQInteger codelen = utf8_lengths[c >> 4];
00351     if (codelen == 0) return 0;
00352 
00353     tmp = c & byte_masks[codelen];
00354     for (SQInteger n = 0; n < codelen - 1; n++) {
00355       tmp <<= 6;
00356       if (((SQFile *)file)->Read(&inchar, sizeof(inchar), 1) != 1) return 0;
00357       tmp |= inchar & 0x3F;
00358     }
00359     c = tmp;
00360   }
00361   return c;
00362 }
00363 
00364 static SQInteger _io_file_lexfeed_UCS2_LE(SQUserPointer file)
00365 {
00366   wchar_t c;
00367   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return (SQChar)c;
00368   return 0;
00369 }
00370 
00371 static SQInteger _io_file_lexfeed_UCS2_BE(SQUserPointer file)
00372 {
00373   unsigned short c;
00374   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) {
00375     c = ((c >> 8) & 0x00FF)| ((c << 8) & 0xFF00);
00376     return (SQChar)c;
00377   }
00378   return 0;
00379 }
00380 
00381 static SQInteger _io_file_read(SQUserPointer file, SQUserPointer buf, SQInteger size)
00382 {
00383   SQInteger ret = ((SQFile *)file)->Read(buf, 1, size);
00384   if (ret == 0) return -1;
00385   return ret;
00386 }
00387 
00388 /* static */ SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const char *filename, SQBool printerror)
00389 {
00390   size_t size;
00391   FILE *file = FioFOpenFile(filename, "rb", AI_DIR, &size);
00392   SQInteger ret;
00393   unsigned short us;
00394   unsigned char uc;
00395   SQLEXREADFUNC func;
00396 
00397   if (file != NULL) {
00398     SQFile f(file, size);
00399     ret = fread(&us, 1, sizeof(us), file);
00400     /* Most likely an empty file */
00401     if (ret != 2) us = 0;
00402 
00403     switch (us) {
00404       case SQ_BYTECODE_STREAM_TAG: { // BYTECODE
00405         fseek(file, -2, SEEK_CUR);
00406         if (SQ_SUCCEEDED(sq_readclosure(vm, _io_file_read, &f))) {
00407           FioFCloseFile(file);
00408           return SQ_OK;
00409         }
00410         FioFCloseFile(file);
00411         return sq_throwerror(vm, _SC("Couldn't read bytecode"));
00412       }
00413       case 0xFFFE: func = _io_file_lexfeed_UCS2_BE; break; // UTF-16 little endian
00414       case 0xFEFF: func = _io_file_lexfeed_UCS2_LE; break; // UTF-16 big endian
00415       case 0xBBEF: // UTF-8
00416         if (fread(&uc, 1, sizeof(uc), file) == 0) {
00417           FioFCloseFile(file);
00418           return sq_throwerror(vm, _SC("I/O error"));
00419         }
00420         if (uc != 0xBF) {
00421           FioFCloseFile(file);
00422           return sq_throwerror(vm, _SC("Unrecognized encoding"));
00423         }
00424         func = _io_file_lexfeed_UTF8;
00425         break;
00426       default: func = _io_file_lexfeed_ASCII; fseek(file, -2, SEEK_CUR); break; // ASCII
00427     }
00428 
00429     if (SQ_SUCCEEDED(sq_compile(vm, func, &f, OTTD2FS(filename), printerror))) {
00430       FioFCloseFile(file);
00431       return SQ_OK;
00432     }
00433     FioFCloseFile(file);
00434     return SQ_ERROR;
00435   }
00436   return sq_throwerror(vm, _SC("cannot open the file"));
00437 }
00438 
00439 /* static */ bool Squirrel::LoadScript(HSQUIRRELVM vm, const char *script, bool in_root)
00440 {
00441   /* Make sure we are always in the root-table */
00442   if (in_root) sq_pushroottable(vm);
00443 
00444   /* Load and run the script */
00445   if (SQ_SUCCEEDED(LoadFile(vm, script, SQTrue))) {
00446     sq_push(vm, -2);
00447     if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue))) {
00448       sq_pop(vm, 1);
00449       return true;
00450     }
00451   }
00452 
00453   DEBUG(misc, 0, "[squirrel] Failed to compile '%s'", script);
00454   return false;
00455 }
00456 
00457 bool Squirrel::LoadScript(const char *script)
00458 {
00459   return LoadScript(this->vm, script);
00460 }
00461 
00462 Squirrel::~Squirrel()
00463 {
00464   /* Clean up the stuff */
00465   sq_pop(this->vm, 1);
00466   sq_close(this->vm);
00467 }
00468 
00469 void Squirrel::InsertResult(bool result)
00470 {
00471   sq_pushbool(this->vm, result);
00472   vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
00473   vm->Pop();
00474 }
00475 
00476 void Squirrel::InsertResult(int result)
00477 {
00478   sq_pushinteger(this->vm, result);
00479   vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
00480   vm->Pop();
00481 }
00482 
00483 /* static */ void Squirrel::DecreaseOps(HSQUIRRELVM vm, int ops)
00484 {
00485   vm->DecreaseOps(ops);
00486 }
00487 
00488 bool Squirrel::IsSuspended()
00489 {
00490   return this->vm->_suspended != 0;
00491 }
00492 
00493 bool Squirrel::HasScriptCrashed()
00494 {
00495   return this->crashed;
00496 }
00497 
00498 void Squirrel::ResetCrashed()
00499 {
00500   this->crashed = false;
00501 }

Generated on Mon Mar 9 23:33:50 2009 for openttd by  doxygen 1.5.6