# squirrel.cpp

Go to the documentation of this file.

    00001 /* $Id: squirrel.cpp 16121 2009-04-22 09:00:19Z 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::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 bool Squirrel::CallBoolMethod(HSQOBJECT instance, const char *method_name, bool *res, int suspend)
    00238 {
    00239   HSQOBJECT ret;
    00240   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
    00241   if (ret._type != OT_BOOL) return false;
    00242   *res = ObjectToBool(&ret);
    00243   return true;
    00244 }
    00245
    00246 /* static */ bool Squirrel::CreateClassInstanceVM(HSQUIRRELVM vm, const char *class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook)
    00247 {
    00248   int oldtop = sq_gettop(vm);
    00249
    00250   /* First, find the class */
    00251   sq_pushroottable(vm);
    00252   sq_pushstring(vm, OTTD2FS(class_name), -1);
    00253   if (SQ_FAILED(sq_get(vm, -2))) {
    00254     DEBUG(misc, 0, "[squirrel] Failed to find class by the name '%s'", class_name);
    00255     sq_settop(vm, oldtop);
    00256     return false;
    00257   }
    00258
    00259   /* Create the instance */
    00260   if (SQ_FAILED(sq_createinstance(vm, -1))) {
    00261     DEBUG(misc, 0, "[squirrel] Failed to create instance for class '%s'", class_name);
    00262     sq_settop(vm, oldtop);
    00263     return false;
    00264   }
    00265
    00266   if (instance != NULL) {
    00267     /* Find our instance */
    00268     sq_getstackobj(vm, -1, instance);
    00269     /* Add a reference to it, so it survives for ever */
    00270     sq_addref(vm, instance);
    00271   }
    00272   sq_remove(vm, -2); // Class-name
    00273   sq_remove(vm, -2); // Root-table
    00274
    00275   /* Store it in the class */
    00276   sq_setinstanceup(vm, -1, real_instance);
    00277   if (release_hook != NULL) sq_setreleasehook(vm, -1, release_hook);
    00278
    00279   if (instance != NULL) sq_settop(vm, oldtop);
    00280
    00281   return true;
    00282 }
    00283
    00284 bool Squirrel::CreateClassInstance(const char *class_name, void *real_instance, HSQOBJECT *instance)
    00285 {
    00286   return Squirrel::CreateClassInstanceVM(this->vm, class_name, real_instance, instance, NULL);
    00287 }
    00288
    00289 Squirrel::Squirrel()
    00290 {
    00291   this->vm = sq_open(1024);
    00292   this->print_func = NULL;
    00293   this->global_pointer = NULL;
    00294   this->crashed = false;
    00295
    00296   /* Handle compile-errors ourself, so we can display it nicely */
    00297   sq_setcompilererrorhandler(this->vm, &Squirrel::CompileError);
    00298   sq_notifyallexceptions(this->vm, SQTrue);
    00299   /* Set a good print-function */
    00300   sq_setprintfunc(this->vm, &Squirrel::PrintFunc);
    00301   /* Handle runtime-errors ourself, so we can display it nicely */
    00302   sq_newclosure(this->vm, &Squirrel::_RunError, 0);
    00303   sq_seterrorhandler(this->vm);
    00304
    00305   /* Set the foreigh pointer, so we can always find this instance from within the VM */
    00306   sq_setforeignptr(this->vm, this);
    00307
    00308   sq_pushroottable(this->vm);
    00309   squirrel_register_global_std(this);
    00310 }
    00311
    00312 class SQFile {
    00313 private:
    00314   FILE *file;
    00315   size_t size;
    00316   size_t pos;
    00317
    00318 public:
    00319   SQFile(FILE *file, size_t size) : file(file), size(size), pos(0) {}
    00320
    00321   size_t Read(void *buf, size_t elemsize, size_t count)
    00322   {
    00323     assert(elemsize != 0);
    00324     if (this->pos + (elemsize * count) > this->size) {
    00325       count = (this->size - this->pos) / elemsize;
    00326     }
    00327     if (count == 0) return 0;
    00328     size_t ret = fread(buf, elemsize, count, this->file);
    00329     this->pos += ret * elemsize;
    00330     return ret;
    00331   }
    00332 };
    00333
    00334 static SQInteger _io_file_lexfeed_ASCII(SQUserPointer file)
    00335 {
    00336   char c;
    00337   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return c;
    00338   return 0;
    00339 }
    00340
    00341 static SQInteger _io_file_lexfeed_UTF8(SQUserPointer file)
    00342 {
    00343   static const SQInteger utf8_lengths[16] =
    00344   {
    00345     1, 1, 1, 1, 1, 1, 1, 1, /* 0000 to 0111 : 1 byte (plain ASCII) */
    00346     0, 0, 0, 0,             /* 1000 to 1011 : not valid */
    00347     2, 2,                   /* 1100, 1101 : 2 bytes */
    00348     3,                      /* 1110 : 3 bytes */
    00349     4                       /* 1111 : 4 bytes */
    00350   };
    00351   static unsigned char byte_masks[5] = {0, 0, 0x1F, 0x0F, 0x07};
    00352   unsigned char inchar;
    00353   SQInteger c = 0;
    00354   if (((SQFile *)file)->Read(&inchar, sizeof(inchar), 1) != 1) return 0;
    00355   c = inchar;
    00356
    00357   if (c >= 0x80) {
    00358     SQInteger tmp;
    00359     SQInteger codelen = utf8_lengths[c >> 4];
    00360     if (codelen == 0) return 0;
    00361
    00362     tmp = c & byte_masks[codelen];
    00363     for (SQInteger n = 0; n < codelen - 1; n++) {
    00364       tmp <<= 6;
    00365       if (((SQFile *)file)->Read(&inchar, sizeof(inchar), 1) != 1) return 0;
    00366       tmp |= inchar & 0x3F;
    00367     }
    00368     c = tmp;
    00369   }
    00370   return c;
    00371 }
    00372
    00373 static SQInteger _io_file_lexfeed_UCS2_LE(SQUserPointer file)
    00374 {
    00375   wchar_t c;
    00376   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return (SQChar)c;
    00377   return 0;
    00378 }
    00379
    00380 static SQInteger _io_file_lexfeed_UCS2_BE(SQUserPointer file)
    00381 {
    00382   unsigned short c;
    00383   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) {
    00384     c = ((c >> 8) & 0x00FF)| ((c << 8) & 0xFF00);
    00385     return (SQChar)c;
    00386   }
    00387   return 0;
    00388 }
    00389
    00390 static SQInteger _io_file_read(SQUserPointer file, SQUserPointer buf, SQInteger size)
    00391 {
    00392   SQInteger ret = ((SQFile *)file)->Read(buf, 1, size);
    00393   if (ret == 0) return -1;
    00394   return ret;
    00395 }
    00396
    00397 /* static */ SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const char *filename, SQBool printerror)
    00398 {
    00399   size_t size;
    00400   FILE *file = FioFOpenFile(filename, "rb", AI_DIR, &size);
    00401   SQInteger ret;
    00402   unsigned short us;
    00403   unsigned char uc;
    00404   SQLEXREADFUNC func;
    00405
    00406   if (file != NULL) {
    00407     SQFile f(file, size);
    00408     ret = fread(&us, 1, sizeof(us), file);
    00409     /* Most likely an empty file */
    00410     if (ret != 2) us = 0;
    00411
    00412     switch (us) {
    00413       case SQ_BYTECODE_STREAM_TAG: { // BYTECODE
    00414         fseek(file, -2, SEEK_CUR);
    00415         if (SQ_SUCCEEDED(sq_readclosure(vm, _io_file_read, &f))) {
    00416           FioFCloseFile(file);
    00417           return SQ_OK;
    00418         }
    00419         FioFCloseFile(file);
    00420         return sq_throwerror(vm, _SC("Couldn't read bytecode"));
    00421       }
    00422       case 0xFFFE: func = _io_file_lexfeed_UCS2_BE; break; // UTF-16 little endian
    00423       case 0xFEFF: func = _io_file_lexfeed_UCS2_LE; break; // UTF-16 big endian
    00424       case 0xBBEF: // UTF-8
    00425         if (fread(&uc, 1, sizeof(uc), file) == 0) {
    00426           FioFCloseFile(file);
    00427           return sq_throwerror(vm, _SC("I/O error"));
    00428         }
    00429         if (uc != 0xBF) {
    00430           FioFCloseFile(file);
    00431           return sq_throwerror(vm, _SC("Unrecognized encoding"));
    00432         }
    00433         func = _io_file_lexfeed_UTF8;
    00434         break;
    00435       default: func = _io_file_lexfeed_ASCII; fseek(file, -2, SEEK_CUR); break; // ASCII
    00436     }
    00437
    00438     if (SQ_SUCCEEDED(sq_compile(vm, func, &f, OTTD2FS(filename), printerror))) {
    00439       FioFCloseFile(file);
    00440       return SQ_OK;
    00441     }
    00442     FioFCloseFile(file);
    00443     return SQ_ERROR;
    00444   }
    00445   return sq_throwerror(vm, _SC("cannot open the file"));
    00446 }
    00447
    00448 /* static */ bool Squirrel::LoadScript(HSQUIRRELVM vm, const char *script, bool in_root)
    00449 {
    00450   /* Make sure we are always in the root-table */
    00451   if (in_root) sq_pushroottable(vm);
    00452
    00453   /* Load and run the script */
    00454   if (SQ_SUCCEEDED(LoadFile(vm, script, SQTrue))) {
    00455     sq_push(vm, -2);
    00456     if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue))) {
    00457       sq_pop(vm, 1);
    00458       return true;
    00459     }
    00460   }
    00461
    00462   DEBUG(misc, 0, "[squirrel] Failed to compile '%s'", script);
    00463   return false;
    00464 }
    00465
    00466 bool Squirrel::LoadScript(const char *script)
    00467 {
    00468   return LoadScript(this->vm, script);
    00469 }
    00470
    00471 Squirrel::~Squirrel()
    00472 {
    00473   /* Clean up the stuff */
    00474   sq_pop(this->vm, 1);
    00475   sq_close(this->vm);
    00476 }
    00477
    00478 void Squirrel::InsertResult(bool result)
    00479 {
    00480   sq_pushbool(this->vm, result);
    00481   vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
    00482   vm->Pop();
    00483 }
    00484
    00485 void Squirrel::InsertResult(int result)
    00486 {
    00487   sq_pushinteger(this->vm, result);
    00488   vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
    00489   vm->Pop();
    00490 }
    00491
    00492 /* static */ void Squirrel::DecreaseOps(HSQUIRRELVM vm, int ops)
    00493 {
    00494   vm->DecreaseOps(ops);
    00495 }
    00496
    00497 bool Squirrel::IsSuspended()
    00498 {
    00499   return this->vm->_suspended != 0;
    00500 }
    00501
    00502 bool Squirrel::HasScriptCrashed()
    00503 {
    00504   return this->crashed;
    00505 }
    00506
    00507 void Squirrel::ResetCrashed()
    00508 {
    00509   this->crashed = false;
    00510 }