squirrel.cpp

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