# squirrel.cpp

Go to the documentation of this file.

    00001 /* $Id: squirrel.cpp 17417 2009-09-04 20:40:15Z rubidium $ */
    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::AddConst(const char *var_name, bool value)
    00135 {
    00136   sq_pushstring(this->vm, OTTD2FS(var_name), -1);
    00137   sq_pushbool(this->vm, value);
    00138   sq_newslot(this->vm, -3, SQTrue);
    00139 }
    00140
    00141 void Squirrel::AddClassBegin(const char *class_name)
    00142 {
    00143   sq_pushroottable(this->vm);
    00144   sq_pushstring(this->vm, OTTD2FS(class_name), -1);
    00145   sq_newclass(this->vm, SQFalse);
    00146 }
    00147
    00148 void Squirrel::AddClassBegin(const char *class_name, const char *parent_class)
    00149 {
    00150   sq_pushroottable(this->vm);
    00151   sq_pushstring(this->vm, OTTD2FS(class_name), -1);
    00152   sq_pushstring(this->vm, OTTD2FS(parent_class), -1);
    00153   if (SQ_FAILED(sq_get(this->vm, -3))) {
    00154     DEBUG(misc, 0, "[squirrel] Failed to initialize class '%s' based on parent class '%s'", class_name, parent_class);
    00155     DEBUG(misc, 0, "[squirrel] Make sure that '%s' exists before trying to define '%s'", parent_class, class_name);
    00156     return;
    00157   }
    00158   sq_newclass(this->vm, SQTrue);
    00159 }
    00160
    00161 void Squirrel::AddClassEnd()
    00162 {
    00163   sq_newslot(vm, -3, SQFalse);
    00164   sq_pop(vm, 1);
    00165 }
    00166
    00167 bool Squirrel::MethodExists(HSQOBJECT instance, const char *method_name)
    00168 {
    00169   assert(!this->crashed);
    00170   int top = sq_gettop(this->vm);
    00171   /* Go to the instance-root */
    00172   sq_pushobject(this->vm, instance);
    00173   /* Find the function-name inside the script */
    00174   sq_pushstring(this->vm, OTTD2FS(method_name), -1);
    00175   if (SQ_FAILED(sq_get(this->vm, -2))) {
    00176     sq_settop(this->vm, top);
    00177     return false;
    00178   }
    00179   sq_settop(this->vm, top);
    00180   return true;
    00181 }
    00182
    00183 bool Squirrel::Resume(int suspend)
    00184 {
    00185   assert(!this->crashed);
    00186   this->crashed = !sq_resumecatch(this->vm, suspend);
    00187   return this->vm->_suspended != 0;
    00188 }
    00189
    00190 void Squirrel::ResumeError()
    00191 {
    00192   assert(!this->crashed);
    00193   sq_resumeerror(this->vm);
    00194 }
    00195
    00196 void Squirrel::CollectGarbage()
    00197 {
    00198   sq_collectgarbage(this->vm);
    00199 }
    00200
    00201 bool Squirrel::CallMethod(HSQOBJECT instance, const char *method_name, HSQOBJECT *ret, int suspend)
    00202 {
    00203   assert(!this->crashed);
    00204   /* Store the stack-location for the return value. We need to
    00205    * restore this after saving or the stack will be corrupted
    00206    * if we're in the middle of a DoCommand. */
    00207   SQInteger last_target = this->vm->_suspended_target;
    00208   /* Store the current top */
    00209   int top = sq_gettop(this->vm);
    00210   /* Go to the instance-root */
    00211   sq_pushobject(this->vm, instance);
    00212   /* Find the function-name inside the script */
    00213   sq_pushstring(this->vm, OTTD2FS(method_name), -1);
    00214   if (SQ_FAILED(sq_get(this->vm, -2))) {
    00215     DEBUG(misc, 0, "[squirrel] Could not find '%s' in the class", method_name);
    00216     sq_settop(this->vm, top);
    00217     return false;
    00218   }
    00219   /* Call the method */
    00220   sq_pushobject(this->vm, instance);
    00221   if (SQ_FAILED(sq_call(this->vm, 1, ret == NULL ? SQFalse : SQTrue, SQTrue, suspend))) return false;
    00222   if (ret != NULL) sq_getstackobj(vm, -1, ret);
    00223   /* Reset the top, but don't do so for the AI main function, as we need
    00224    *  a correct stack when resuming. */
    00225   if (suspend == -1) sq_settop(this->vm, top);
    00226   /* Restore the return-value location. */
    00227   this->vm->_suspended_target = last_target;
    00228
    00229   return true;
    00230 }
    00231
    00232 bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance, const char *method_name, const char **res, int suspend)
    00233 {
    00234   HSQOBJECT ret;
    00235   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
    00236   if (ret._type != OT_STRING) return false;
    00237   *res = strdup(ObjectToString(&ret));
    00238   return true;
    00239 }
    00240
    00241 bool Squirrel::CallIntegerMethod(HSQOBJECT instance, const char *method_name, int *res, int suspend)
    00242 {
    00243   HSQOBJECT ret;
    00244   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
    00245   if (ret._type != OT_INTEGER) return false;
    00246   *res = ObjectToInteger(&ret);
    00247   return true;
    00248 }
    00249
    00250 bool Squirrel::CallBoolMethod(HSQOBJECT instance, const char *method_name, bool *res, int suspend)
    00251 {
    00252   HSQOBJECT ret;
    00253   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
    00254   if (ret._type != OT_BOOL) return false;
    00255   *res = ObjectToBool(&ret);
    00256   return true;
    00257 }
    00258
    00259 /* static */ bool Squirrel::CreateClassInstanceVM(HSQUIRRELVM vm, const char *class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook)
    00260 {
    00261   int oldtop = sq_gettop(vm);
    00262
    00263   /* First, find the class */
    00264   sq_pushroottable(vm);
    00265   sq_pushstring(vm, OTTD2FS(class_name), -1);
    00266   if (SQ_FAILED(sq_get(vm, -2))) {
    00267     DEBUG(misc, 0, "[squirrel] Failed to find class by the name '%s'", class_name);
    00268     sq_settop(vm, oldtop);
    00269     return false;
    00270   }
    00271
    00272   /* Create the instance */
    00273   if (SQ_FAILED(sq_createinstance(vm, -1))) {
    00274     DEBUG(misc, 0, "[squirrel] Failed to create instance for class '%s'", class_name);
    00275     sq_settop(vm, oldtop);
    00276     return false;
    00277   }
    00278
    00279   if (instance != NULL) {
    00280     /* Find our instance */
    00281     sq_getstackobj(vm, -1, instance);
    00282     /* Add a reference to it, so it survives for ever */
    00283     sq_addref(vm, instance);
    00284   }
    00285   sq_remove(vm, -2); // Class-name
    00286   sq_remove(vm, -2); // Root-table
    00287
    00288   /* Store it in the class */
    00289   sq_setinstanceup(vm, -1, real_instance);
    00290   if (release_hook != NULL) sq_setreleasehook(vm, -1, release_hook);
    00291
    00292   if (instance != NULL) sq_settop(vm, oldtop);
    00293
    00294   return true;
    00295 }
    00296
    00297 bool Squirrel::CreateClassInstance(const char *class_name, void *real_instance, HSQOBJECT *instance)
    00298 {
    00299   return Squirrel::CreateClassInstanceVM(this->vm, class_name, real_instance, instance, NULL);
    00300 }
    00301
    00302 Squirrel::Squirrel()
    00303 {
    00304   this->vm = sq_open(1024);
    00305   this->print_func = NULL;
    00306   this->global_pointer = NULL;
    00307   this->crashed = false;
    00308
    00309   /* Handle compile-errors ourself, so we can display it nicely */
    00310   sq_setcompilererrorhandler(this->vm, &Squirrel::CompileError);
    00311   sq_notifyallexceptions(this->vm, SQTrue);
    00312   /* Set a good print-function */
    00313   sq_setprintfunc(this->vm, &Squirrel::PrintFunc);
    00314   /* Handle runtime-errors ourself, so we can display it nicely */
    00315   sq_newclosure(this->vm, &Squirrel::_RunError, 0);
    00316   sq_seterrorhandler(this->vm);
    00317
    00318   /* Set the foreigh pointer, so we can always find this instance from within the VM */
    00319   sq_setforeignptr(this->vm, this);
    00320
    00321   sq_pushroottable(this->vm);
    00322   squirrel_register_global_std(this);
    00323 }
    00324
    00325 class SQFile {
    00326 private:
    00327   FILE *file;
    00328   size_t size;
    00329   size_t pos;
    00330
    00331 public:
    00332   SQFile(FILE *file, size_t size) : file(file), size(size), pos(0) {}
    00333
    00334   size_t Read(void *buf, size_t elemsize, size_t count)
    00335   {
    00336     assert(elemsize != 0);
    00337     if (this->pos + (elemsize * count) > this->size) {
    00338       count = (this->size - this->pos) / elemsize;
    00339     }
    00340     if (count == 0) return 0;
    00341     size_t ret = fread(buf, elemsize, count, this->file);
    00342     this->pos += ret * elemsize;
    00343     return ret;
    00344   }
    00345 };
    00346
    00347 static SQInteger _io_file_lexfeed_ASCII(SQUserPointer file)
    00348 {
    00349   char c;
    00350   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return c;
    00351   return 0;
    00352 }
    00353
    00354 static SQInteger _io_file_lexfeed_UTF8(SQUserPointer file)
    00355 {
    00356   static const SQInteger utf8_lengths[16] =
    00357   {
    00358     1, 1, 1, 1, 1, 1, 1, 1, /* 0000 to 0111 : 1 byte (plain ASCII) */
    00359     0, 0, 0, 0,             /* 1000 to 1011 : not valid */
    00360     2, 2,                   /* 1100, 1101 : 2 bytes */
    00361     3,                      /* 1110 : 3 bytes */
    00362     4                       /* 1111 : 4 bytes */
    00363   };
    00364   static unsigned char byte_masks[5] = {0, 0, 0x1F, 0x0F, 0x07};
    00365   unsigned char inchar;
    00366   SQInteger c = 0;
    00367   if (((SQFile *)file)->Read(&inchar, sizeof(inchar), 1) != 1) return 0;
    00368   c = inchar;
    00369
    00370   if (c >= 0x80) {
    00371     SQInteger tmp;
    00372     SQInteger codelen = utf8_lengths[c >> 4];
    00373     if (codelen == 0) return 0;
    00374
    00375     tmp = c & byte_masks[codelen];
    00376     for (SQInteger n = 0; n < codelen - 1; n++) {
    00377       tmp <<= 6;
    00378       if (((SQFile *)file)->Read(&inchar, sizeof(inchar), 1) != 1) return 0;
    00379       tmp |= inchar & 0x3F;
    00380     }
    00381     c = tmp;
    00382   }
    00383   return c;
    00384 }
    00385
    00386 static SQInteger _io_file_lexfeed_UCS2_LE(SQUserPointer file)
    00387 {
    00388   wchar_t c;
    00389   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return (SQChar)c;
    00390   return 0;
    00391 }
    00392
    00393 static SQInteger _io_file_lexfeed_UCS2_BE(SQUserPointer file)
    00394 {
    00395   unsigned short c;
    00396   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) {
    00397     c = ((c >> 8) & 0x00FF)| ((c << 8) & 0xFF00);
    00398     return (SQChar)c;
    00399   }
    00400   return 0;
    00401 }
    00402
    00403 static SQInteger _io_file_read(SQUserPointer file, SQUserPointer buf, SQInteger size)
    00404 {
    00405   SQInteger ret = ((SQFile *)file)->Read(buf, 1, size);
    00406   if (ret == 0) return -1;
    00407   return ret;
    00408 }
    00409
    00410 /* static */ SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const char *filename, SQBool printerror)
    00411 {
    00412   size_t size;
    00413   FILE *file = FioFOpenFile(filename, "rb", AI_DIR, &size);
    00414   SQInteger ret;
    00415   unsigned short us;
    00416   unsigned char uc;
    00417   SQLEXREADFUNC func;
    00418
    00419   if (file != NULL) {
    00420     SQFile f(file, size);
    00421     ret = fread(&us, 1, sizeof(us), file);
    00422     /* Most likely an empty file */
    00423     if (ret != 2) us = 0;
    00424
    00425     switch (us) {
    00426       case SQ_BYTECODE_STREAM_TAG: { // BYTECODE
    00427         fseek(file, -2, SEEK_CUR);
    00428         if (SQ_SUCCEEDED(sq_readclosure(vm, _io_file_read, &f))) {
    00429           FioFCloseFile(file);
    00430           return SQ_OK;
    00431         }
    00432         FioFCloseFile(file);
    00433         return sq_throwerror(vm, _SC("Couldn't read bytecode"));
    00434       }
    00435       case 0xFFFE: func = _io_file_lexfeed_UCS2_BE; break; // UTF-16 little endian
    00436       case 0xFEFF: func = _io_file_lexfeed_UCS2_LE; break; // UTF-16 big endian
    00437       case 0xBBEF: // UTF-8
    00438         if (fread(&uc, 1, sizeof(uc), file) == 0) {
    00439           FioFCloseFile(file);
    00440           return sq_throwerror(vm, _SC("I/O error"));
    00441         }
    00442         if (uc != 0xBF) {
    00443           FioFCloseFile(file);
    00444           return sq_throwerror(vm, _SC("Unrecognized encoding"));
    00445         }
    00446         func = _io_file_lexfeed_UTF8;
    00447         break;
    00448       default: func = _io_file_lexfeed_ASCII; fseek(file, -2, SEEK_CUR); break; // ASCII
    00449     }
    00450
    00451     if (SQ_SUCCEEDED(sq_compile(vm, func, &f, OTTD2FS(filename), printerror))) {
    00452       FioFCloseFile(file);
    00453       return SQ_OK;
    00454     }
    00455     FioFCloseFile(file);
    00456     return SQ_ERROR;
    00457   }
    00458   return sq_throwerror(vm, _SC("cannot open the file"));
    00459 }
    00460
    00461 /* static */ bool Squirrel::LoadScript(HSQUIRRELVM vm, const char *script, bool in_root)
    00462 {
    00463   /* Make sure we are always in the root-table */
    00464   if (in_root) sq_pushroottable(vm);
    00465
    00466   /* Load and run the script */
    00467   if (SQ_SUCCEEDED(LoadFile(vm, script, SQTrue))) {
    00468     sq_push(vm, -2);
    00469     if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue))) {
    00470       sq_pop(vm, 1);
    00471       return true;
    00472     }
    00473   }
    00474
    00475   DEBUG(misc, 0, "[squirrel] Failed to compile '%s'", script);
    00476   return false;
    00477 }
    00478
    00479 bool Squirrel::LoadScript(const char *script)
    00480 {
    00481   return LoadScript(this->vm, script);
    00482 }
    00483
    00484 Squirrel::~Squirrel()
    00485 {
    00486   /* Clean up the stuff */
    00487   sq_pop(this->vm, 1);
    00488   sq_close(this->vm);
    00489 }
    00490
    00491 void Squirrel::InsertResult(bool result)
    00492 {
    00493   sq_pushbool(this->vm, result);
    00494   vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
    00495   vm->Pop();
    00496 }
    00497
    00498 void Squirrel::InsertResult(int result)
    00499 {
    00500   sq_pushinteger(this->vm, result);
    00501   vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
    00502   vm->Pop();
    00503 }
    00504
    00505 /* static */ void Squirrel::DecreaseOps(HSQUIRRELVM vm, int ops)
    00506 {
    00507   vm->DecreaseOps(ops);
    00508 }
    00509
    00510 bool Squirrel::IsSuspended()
    00511 {
    00512   return this->vm->_suspended != 0;
    00513 }
    00514
    00515 bool Squirrel::HasScriptCrashed()
    00516 {
    00517   return this->crashed;
    00518 }
    00519
    00520 void Squirrel::ResetCrashed()
    00521 {
    00522   this->crashed = false;
    00523 }
    00524
    00525 void Squirrel::CrashOccurred()
    00526 {
    00527   this->crashed = true;
    00528 }
    00529
    00530 bool Squirrel::CanSuspend()
    00531 {
    00532   return sq_can_suspend(this->vm);
    00533 }