# squirrel.cpp

Go to the documentation of this file.

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