squirrel.cpp

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

Generated on Sun May 8 07:30:18 2011 for OpenTTD by  doxygen 1.6.1